我有一个非空格字符之间有2,3或更多空格的字符串
string = "a b c d"
Run Code Online (Sandbox Code Playgroud)
我能做些什么来做到这一点:
output_string == "a b c d"
Run Code Online (Sandbox Code Playgroud)
Dog*_*ert 13
最简单的方法是使用正则表达式:
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"
Run Code Online (Sandbox Code Playgroud)
就其价值而言,您甚至不需要正则表达式:
iex(3)> "a b c d" |> String.split |> Enum.join(" ")
#=>"a b c d"
Run Code Online (Sandbox Code Playgroud)
也只是从我的一点点烟雾测试来看,它看起来可以与任何空白分隔符一起使用(即据我所知,它适用于空格和制表符)。