问题
I have a string of four blank lines which all up makes eight lines in total in the following:
str = "aaa\n\n\nbbb\n\nccc\ddd\n"
I want to return this all in one line. The output should be like this on a single line:
aaabbbcccddd
I used various trim functions to get the output but still I am failing.
What method do I have to use here?
回答1:
The Ruby (and slightly less Perl-ish) way:
new_str = str.delete "\n"
...or if you want to do it in-place:
str.delete! "\n"
回答2:
str.gsub(/\n/,'')
回答3:
> str = "aaa\n\n\nbbb\n\nccc\ddd\n"
=> "aaa\n\n\nbbb\n\ncccddd\n"
> str.gsub("\n", "")
=> "aaabbbcccddd"
来源:https://stackoverflow.com/questions/1040390/trim-blank-newlines-from-string-in-ruby