如何用整个字符串中的单个空格替换连续的空格 [英] How can I replace consecutive whitespace with a single space from the whole string

查看:86
本文介绍了如何用整个字符串中的单个空格替换连续的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,在非空格字符之间有2.3个或更多空格

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

string = "a  b c   d"

我该怎么做才能做到:

output_string == "a b c d"


推荐答案

最简单的方法是使用正则表达式:

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"

这篇关于如何用整个字符串中的单个空格替换连续的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆