Ruby中常用的字符串处理函数使用实例

2019-09-25 09:46:36刘景俊


str.lstrip => new_str
" hello ".lstrip   #=> "hello "
"hello".lstrip       #=> "hello"

8.字符串匹配

str.match(pattern) => matchdata or nil

9.字符串反转

str.reverse => new_str
"stressed".reverse   #=> "desserts"

10.去掉重复的字符

str.squeeze([other_str]*) => new_str
"yellow moon".squeeze                  #=> "yelow mon" #默认去掉串中所有重复的字符
" now   is the".squeeze(" ")         #=> " now is the" #去掉串中重复的空格
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls" #去掉指定范围内的重复字符

11.转化成数字

str.to_i=> str
"12345".to_i             #=> 12345

chomp和chop的区别:

chomp:去掉字符串末尾的n或r
chop:去掉字符串末尾的最后一个字符,不管是nr还是普通字符


"hello".chomp            #=> "hello"
"hellon".chomp          #=> "hello"
"hellorn".chomp        #=> "hello"
"hellonr".chomp        #=> "hellon"
"hellor".chomp          #=> "hello"
"hello".chomp("llo")     #=> "he"

"stringrn".chop   #=> "string"
"stringnr".chop   #=> "stringn"
"stringn".chop     #=> "string"
"string".chop       #=> "strin"

split是String类的一个类方法,我根据ri String.split提供的内容简单翻译一下。
----------------------------------------------------------- String#split
str.split(pattern=$;, [limit]) => anArray
------------------------------------------------------------------------
Divides _str_ into substrings based on a delimiter, returning an
array of these substrings.
将一个字符串用分隔符分割成一些子字符串,并返回一个包含这些子字符串的数组。

If _pattern_ is a +String+, then its contents are used as the
delimiter when splitting _str_. If _pattern_ is a single space,
_str_ is split on whitespace, with leading whitespace and runs of
contiguous whitespace characters ignored.
如果pattern部分是一个字符串,那么用它作分割符来分隔,如果pattern是一个空格,那么在空格处分割,并且临近的空格被忽略。