如何在字符串中去除额外的空格和换行符?

4
我有一个字符串变量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的新手,请问有人能告诉我应该如何实现吗?


2
看一下Java中的正则表达式。 - Ramandeep Nanda
你的规则似乎不一致。如果你使用_确切的_格式规则编辑你的问题,你可能会得到一个有用的答案。 - Tim Biegeleisen
你可以通过使用条件语句来遍历字符串并复制所有不是 \n 或任何其他字符的字符。 - Sourav Kanta
我已经实现了除了如何删除单词和“,”、“。”或“;”之间所有空格的规则(单词首次出现)的所有规则。 - Sam Sonnell
6个回答

4
我是Apache Commons Lang库的忠实粉丝,StringUtils类(具有其空值安全函数)已经帮助我省去了无数个小时。毫不奇怪,StringUtils有一个可以满足您要求的函数:StringUtils.normalizeSpace(String str) 从API中得知: 该函数使用trim(String)删除前导和尾随空格,然后将连续的空格字符序列替换为单个空格,从而返回参数字符串的空格规范化版本。

3
Regexs唯一的问题是它们可能会相当慢。如果您愿意使用外部库,请尝试Google Guava库及其CharMatcher。
CharMatcher.whitespace().collapseFrom("Hello There\nMy name is Fred   ", ' '))

这将把空白转换为单个空格,并将多个连续的空白序列合并成一个序列。

2
尝试使用这个:(@Criti的方法)
    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.

你的解决方案中没有去除单词和 '.' 或 ';' 之间的空格。例如:'this is cool . that is hot.' 没有被改为 'this is cool. that is hot.' - Sam Sonnell
编辑过了,请您再试一次。 - David Pérez Cabrera

1

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

这段代码是关于字符串操作的,它的作用是将字符串中的换行符替换为空格,并去除多余的空格。

0
一种方法是逐个字符解析字符串变量。例如:
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);

0

试试这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接