How can I replace consecutive whitespace with a single space from the whole string

吃可爱长大的小学妹 提交于 2019-12-23 09:26:43

问题


I have a string with 2,3 or more spaces between non-space characters

string = "a  b c   d"

What can I do to make it like that:

output_string == "a b c d"

回答1:


The simplest way would be using Regular Expressions:

iex(1)> string = "a  b c   d"
"a  b c   d"
iex(2)> String.replace(string, ~r/ +/, " ") # replace only consecutive space characters
"a b c d"
iex(3)> String.replace(string, ~r/\s+/, " ") # replace any consecutive whitespace
"a b c d"



回答2:


For what it's worth, you don't even need the regex:

iex(3)> "a b c    d" |> String.split |> Enum.join(" ")
#=>"a b c d"

Also just from my very little bit of smoke testing, it looks like this will work with any whitespace separators (i. e. it works on spaces and tabs as far as I can tell).




回答3:


Another possibility would be to String#split and Enum#join:

iex(1)> "a  b c   d" |> String.split(~r{\s+}) |> Enum.join(" ")
#⇒ "a b c d"



回答4:


Regex.replace(~r/\s+/, "a b c d", " ")



来源:https://stackoverflow.com/questions/39393177/how-can-i-replace-consecutive-whitespace-with-a-single-space-from-the-whole-stri

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