Ruby字符串增加或删除空白符号处理

Ruby 定义去掉空格的方法整理:

str.gsub(pattern,replacement):替换部分字符串

"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s.ord.to_s + ' '}      #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}')  #=> "h{e}ll{o}"
'hello'.gsub(/[eo]/, 'e' => 3, 'o' => '*')    #=> "h3ll*"
' he l l o  '.gsub(' ','') #=> "hello"

 

str.strip:返回一个去掉前后空格的字符串

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"
"  hello  ".lstrip   #=> "hello  "
"hello".lstrip       #=> "hello"
"  hello  ".rstrip   #=> "  hello"
"hello".rstrip       #=> "hello"

 

str.chomp:去掉字符串末尾的 \n \r 或 \r\n

"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"

 

str.chop:删除字符串最后一个字符,若结束符是\r\n则两个字符都删除,若字符串为空则返回空

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""

 

str.ljust(integer,padstr=' '):如果integer大于str长度,返回一个长度为integer,str在左边padstr填充的字符串

"hello".ljust(4)            #=> "hello"
"hello".ljust(20)           #=> "hello               "
"hello".ljust(20, '1234')   #=> "hello123412341234123"

 

str.rjust(integer,padstr=' '):如果integer大于str长度,返回一个长度为integer,str在右边padstr填充的字符串

"hello".rjust(4)            #=> "hello"
"hello".rjust(20)           #=> "               hello"
"hello".rjust(20, '1234')   #=> "123412341234123hello"

 

str.center(width,padstr=' '):如果width大约str长度,返回一个长度为width,str在中间两边padstr填充的字符串

"hello".center(4)         #=> "hello"
"hello".center(20)        #=> "       hello        "
"hello".center(20, '123') #=> "1231231hello12312312"

 

你可能感兴趣的:(Ruby字符串增加或删除空白符号处理)