簡體   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