Recipe 1.4. Reversing a String by Words or Characters
Problem
解决字符串里面的单词或者字母的次序不对的问题.
Solution
如果需要从原始字符串创建一个新的反转的字符串,你可以使用reverse方法.
如果需要反转原始字符串本身,可以使用reverse!方法.
s = ".sdrawkcab si gnirts sihT"
s.reverse # => "This string is backwards."
s # => ".sdrawkcab si gnirts sihT"
s.
reverse! # => "This string is backwards."
s # => "This string is backwards."
如果需要反转字符串里面的单词,你可以split这个字符串到一个数组,然后再join这个数组成为一个字符串.
s = "order. wrong the in are words These"
s.split(/(/s+)/).reverse!.join('') # => "These words are in the wrong order."
s.split(//b/).reverse!.join('') # => "These words are in the wrong. order"
Discussion
String#split使用一个正则表达式作为一个分隔符.每次这个分隔符被匹配到后,分隔符前面的那部分就放到一个列表里面.然后split反复的
检查这个字符串剩下的部分.这个查找的结果就是把每次分隔的结果生成一个列表.
正则表达式/(/s+)/匹配一个或多个whitespace characters,相当于[ /t/n/r/f].this splits the string on word boundaries,
which works for us because we want to reverse the order of the words.
正则表达式 /b 匹配一个单词的边界.这个和匹配whitespace不同, 它也会去匹配标点符号.请注意这种匹配结果中标点符号导致的差异.
因为正则表达式 /(/s+)/ 包含了一对圆刮号,这样分隔符也会包含在返回的列表里面.这样,后面join这个列表的时候,whitespace也会被
保留下来.下面的例子显示了有一对圆刮号和没有圆刮号的区别:
"Three little words".split(//s+/) # => ["Three", "little", "words"]
"Three little words".split(/(/s+)/)
# => ["Three", " ", "little", " ", "words"]
See Also
Recipe 1.9, "Processing a String One Word at a Time," has some regular expressions for alternative definitions of "word"
Recipe 1.11, "Managing Whitespace"
Recipe 1.17, "Matching Strings with Regular Expressions"
Problem
解决字符串里面的单词或者字母的次序不对的问题.
Solution
如果需要从原始字符串创建一个新的反转的字符串,你可以使用reverse方法.
如果需要反转原始字符串本身,可以使用reverse!方法.
s = ".sdrawkcab si gnirts sihT"
s.reverse # => "This string is backwards."
s # => ".sdrawkcab si gnirts sihT"
s.
reverse! # => "This string is backwards."
s # => "This string is backwards."
如果需要反转字符串里面的单词,你可以split这个字符串到一个数组,然后再join这个数组成为一个字符串.
s = "order. wrong the in are words These"
s.split(/(/s+)/).reverse!.join('') # => "These words are in the wrong order."
s.split(//b/).reverse!.join('') # => "These words are in the wrong. order"
Discussion
String#split使用一个正则表达式作为一个分隔符.每次这个分隔符被匹配到后,分隔符前面的那部分就放到一个列表里面.然后split反复的
检查这个字符串剩下的部分.这个查找的结果就是把每次分隔的结果生成一个列表.
正则表达式/(/s+)/匹配一个或多个whitespace characters,相当于[ /t/n/r/f].this splits the string on word boundaries,
which works for us because we want to reverse the order of the words.
正则表达式 /b 匹配一个单词的边界.这个和匹配whitespace不同, 它也会去匹配标点符号.请注意这种匹配结果中标点符号导致的差异.
因为正则表达式 /(/s+)/ 包含了一对圆刮号,这样分隔符也会包含在返回的列表里面.这样,后面join这个列表的时候,whitespace也会被
保留下来.下面的例子显示了有一对圆刮号和没有圆刮号的区别:
"Three little words".split(//s+/) # => ["Three", "little", "words"]
"Three little words".split(/(/s+)/)
# => ["Three", " ", "little", " ", "words"]
See Also
Recipe 1.9, "Processing a String One Word at a Time," has some regular expressions for alternative definitions of "word"
Recipe 1.11, "Managing Whitespace"
Recipe 1.17, "Matching Strings with Regular Expressions"