我想用fixnum(它是blank spaces
的數字)替換字符串中的每個blank spaces
。字符串:用數字替換空格
讓我舉一個例子:
s = "hello, how are you ?"
omg(s) # => "hello,3how10are2you1?"
你看到的方式(性感如果可能的話)來更新這樣的字符串?
謝謝Rubists :)
我想用fixnum(它是blank spaces
的數字)替換字符串中的每個blank spaces
。字符串:用數字替換空格
讓我舉一個例子:
s = "hello, how are you ?"
omg(s) # => "hello,3how10are2you1?"
你看到的方式(性感如果可能的話)來更新這樣的字符串?
謝謝Rubists :)
gsub
最好能需要爲「替換爲」參數提供一個塊,塊的結果被插入到找到匹配的地方。該塊的參數是匹配的字符串。因此,爲了實現這一點,我們捕獲儘可能多的空白(/\s+/
),並在每次找到節時將其填充到塊中,然後返回該字符串的長度,然後將其放回原來找到空白處。
代碼:
s = "hello, how are you ?"
res = s.gsub(/\s+/) { |m| m.length }
puts res
# => hello,3how10are2you1?
則可以通過一個數組拆分做到這一點:JavaScript示例
var s = "hello, how are you ?";
function omg(str) {
var strArr = str.split('');
var count = 0;
var finalStr = '';
for(var i = 0; i < strArr.length; i++) {
if(strArr[i] == ' ') {
count++;
}
else
{
if(count > 0) {
finalStr += '' + count;
count = 0;
}
finalStr += strArr[i];
}
}
return finalStr
}
alert(omg(s)); //"hello,3how10are2you1?"
大聲笑,這似乎也可以是對JavaScript
-1因爲OP不使用JavaScript。 – 2011-06-11 23:18:50
謝謝@ pico.creator。我想在Ruby中這樣做,但是你的一段代碼也很有用,所以我無論如何都要加上+1 :) – 2011-06-11 23:24:21
嗯,我認爲它很容易轉換,並不是一個好的ruby用戶。所以這個例子可以很容易理解 – PicoCreator 2011-06-11 23:26:10
如果它包含一個解釋,我會有+1這個答案。 – 2011-06-11 23:20:26
真棒解決方案。 – 2011-06-11 23:21:31
描述加入 – ctcherry 2011-06-11 23:29:19