Trim blank newlines from string in Ruby

自古美人都是妖i 提交于 2019-12-10 19:55:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!