繁体   English   中英

如何删除字符串中的额外空格和新行?

[英]How to remove extra spaces and new lines in a string?

我有一个字符串变量s,就像一个段落的组合。 例如,

Passages provides funeral and burial products.

Our products are meant to align with your values and bring you comfort.

Our products allow you to offer personalization , flexibility and innovative choices, helping you provide services to a wider range of customers.

我必须创建这种形式的字符串变量:

Passages provides funeral and burial products. Our products are meant to align with your values and bring you comfort. Our products allow you to offer personalization, flexibility and innovative choices, helping you provide services to a wider range of customers.

另外,单词之间的额外空格将被删除(或者在'。'和单词的第一行之间),转换为单个空格和',','。'之前的任意数量的空格。 要么 ';' 将被删除。

我是java的新手。 谁能告诉我怎么办?

试试这个:(@ Criti's way)

    String s = "Passages provides funeral and burial products.\n"
            + "Our products are meant to align with your values and bring you comfort.\n"
            + "Our products allow you to offer personalization , flexibility and innovative choices, helping you provide services to a wider range of customers.";

    s = s.replaceAll("\\s*\\.\\s*\n\\s*", ". ");
    s = s.replaceAll("\\s*,\\s*", ", ");
    s = s.replaceAll("\\s*;\\s*", "; ");
    System.out.println(s);

输出:

Passages provides funeral and burial products. Our products are meant to align with your values and bring you comfort. Our products allow you to offer personalization, flexibility and innovative choices, helping you provide services to a wider range of customers.

string.replaceAll("\\n", "").replaceAll("\\\\s+", " ")

正则表达式的唯一问题是它们可能非常慢。 如果您愿意使用外部库,请尝试Google Guava库及其CharMatcher

CharMatcher.WHITESPACE.collapseFrom(“Hello There \\ n我的名字是Fred”,''))

这会将空白转换为单个空格,并将多个空白序列折叠为单个序列。

一种方法是逐个字符地解析String变量。 例如

StringBuilder sb = new StringBuilder();
String toBeParse = "...";
for (int i = 0; i < toBeParse.length(); i++) {
    if (toBeParse.charAt(i) == condition) {
        sb.append(toBeParse.charAt(i));
    }
}
String result = sb.toString();

另一种方法是使用常规表达式:

toBeParse.replaceAll(yourRegexString, replacement);

试试这个

str = str.replaceAll("\\.\\s+(\\w)", ". $1");

我是Apache Commons Lang库的忠实粉丝 - StringUtils类(具有零安全功能)多年来为我节省了无数个小时。 毫不奇怪, StringUtils有一个功能StringUtils您的需求: StringUtils.normalizeSpace(String str)

来自API:

该函数返回带有空格的参数字符串,使用trim(String)删除前导和尾随空格,然后用空格替换空格字符序列。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM