去除所有空白的Ruby函数是什么?我正在寻找一些类似于PHP的trim()?


当前回答

s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

s = "   I have leading and trailing white space   ".strip

其他回答

s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

s = "   I have leading and trailing white space   ".strip

我个人倾向于使用.tr方法

如:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"

感谢@FrankScmitt指出,要删除所有空白(不仅仅是空格),你需要这样写:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"

现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣

如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"

String#strip -删除开头和结尾的所有空白。

字符串#lstrip -只是从开始。

String#rstrip -只从末尾开始。

String#chomp(不带参数)-从末尾删除行分隔符(\n或\r\n)。

String#chop -删除最后一个字符。

x.delete(" \t\r\n")删除所有列出的空白。

String#gsub - x.gsub(/[[:space:]]/, ") -删除所有空白,包括unicode空白。


注意:上面所有的方法都返回一个新的字符串,而不是改变原来的字符串。如果您想就地更改字符串,请使用!最后。

gsub方法就可以了。 gsub方法可以在字符串上调用,并说:

a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring

gsub方法搜索第一个参数的每一次出现 然后用第二个参数替换它。在这种情况下,它将替换字符串中的每个空格并删除它。

另一个例子:

b = "the white fox has a torn tail"

我们把所有出现的字母t都换成大写的t

b = b.gsub("t","T")
puts b 
#Output: The whiTe fox has a Torn Tail