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

本文介绍了Ruby语言中字符串处理的各种实用方法,包括替换、去除空格、截取等常见操作,并展示了具体的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值