Recipe 1.4. Reversing a String by Words or Characters

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"
 

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值