2013-03-14 8 views
10

मुझे एक विशिष्ट आकार के अनुसार एक स्ट्रिंग को टुकड़ों में विभाजित करने की आवश्यकता है। मैं हिस्सों के बीच शब्दों को तोड़ नहीं सकता, इसलिए मुझे अगले शब्द को जोड़ने के दौरान पकड़ने की आवश्यकता है, जो खंड के आकार पर जायेगा और अगला शुरू होगा (यह ठीक है अगर एक खंड निर्दिष्ट आकार से कम है)।शब्दों को तोड़ने के बिना निर्दिष्ट आकार के हिस्सों में एक स्ट्रिंग को विभाजित करें

यहां मेरा कामकाजी कोड है, लेकिन मैं ऐसा करने के लिए एक और अधिक शानदार तरीका खोजना चाहता हूं।

def split_into_chunks_by_size(chunk_size, string) 
    string_split_into_chunks = [""] 
    string.split(" ").each do |word| 
    if (string_split_into_chunks[-1].length + 1 + word.length > chunk_size) 
     string_split_into_chunks << word 
    else 
     string_split_into_chunks[-1] << " " + word 
    end 
    end 
    return string_split_into_chunks 
end 

उत्तर

20

कैसे के बारे में:

str = "split a string into chunks according to a specific size. Seems easy enough, but here is the catch: I cannot be breaking words between chunks, so I need to catch when adding the next word will go over chunk size and start the next one (its ok if a chunk is less than specified size)." 
str.scan(/.{1,25}\W/) 
=> ["split a string into ", "chunks according to a ", "specific size. Seems easy ", "enough, but here is the ", "catch: I cannot be ", "breaking words between ", "chunks, so I need to ", "catch when adding the ", "next word will go over ", "chunk size and start the ", "next one (its ok if a ", "chunk is less than ", "specified size)."] 

अद्यतन @sawa टिप्पणी के बाद:

str.scan(/.{1,25}\b|.{1,25}/).map(&:strip) 

यह बेहतर यह डब्ल्यू

के साथ \ समाप्त करने के लिए एक स्ट्रिंग की आवश्यकता नहीं है के रूप में है और यह निर्दिष्ट लंबाई से अधिक लंबे समय तक शब्दों को संभालेगा। असल में यह उन्हें विभाजित करेगा, लेकिन मुझे लगता है कि यह वांछित व्यवहार

+0

बहुत अच्छा काम करता है, बहुत बहुत धन्यवाद! एक और बात: क्या हम यहां पीछे की जगहों को ट्रिम कर सकते हैं? – psychickita

+0

बेशक: 'str.scan (/। {1,25} \ W /)। नक्शा (&: स्ट्रिप)' –

+1

यह अच्छा है, लेकिन इसे हमेशा अंत में एक '\ W' वर्ण की आवश्यकता होती है। आपके विशेष उदाहरण में, यह अंत में ')' और '.' के कारण काम करता था, लेकिन इसके बिना, यह काम नहीं करेगा। प्रत्येक खंड भी आवश्यक रूप से '\ W' वर्ण के साथ समाप्त होता है जब इसे करने की आवश्यकता नहीं होती है। – sawa

5

@Yuriy, आपका विकल्प परेशानी जैसा दिखता है। कैसे:

str.scan /\S.{1,24}(?!\S)/ 
#=> ["split a string into", "chunks according to a", "specific size. Seems easy", "enough, but here is the", "catch: I cannot be", "breaking words between", "chunks, so I need to", "catch when adding the", "next word will go over", "chunk size and Start the", "next one (its ok if a", "chunk is less than", "specified size)."] 
+0

हाँ, यह बेहतर लगता है, लेकिन यह 25 प्रतीकों से अधिक लंबे समय तक शब्दों को छोटा कर देगा। –

संबंधित मुद्दे

 संबंधित मुद्दे