簡體   English   中英

刪除字符串中 - 前后的空格

[英]remove space before and after - in the string

我正在嘗試刪除字符串中的多余空格。為此,我在 StringUtils 類中使用了 normalizeSpace 方法。 但問題是它沒有刪除“-”前后的空格

public static void main(String[] args)
{
String test = "  Hi   -  World    Java";
System.out.println(StringUtils.normalizeSpace(test));
}

輸出為:“Hi-World Java” 預期輸出為:“Hi-World Java”

有什么輸入嗎?

注意:以下票證解決方案是在連接字符串期間。 因為我們在單個字符串中有數據。 所以這張票不是重復票。 刪除字符串中標點符號前的空格

test = test.replaceAll("[  ]+"," ");
test = test.replaceAll("- ","-");
test = test.replaceAll(" -","-");
test = test.replaceAll("^\\s+",""); 

該實用程序會刪除所有多余的空格,但會留下一個空格。 換句話說,當它找到一個以上空格的序列時,它會刪除除一個空格之外的所有空格。 所以你的結果符合預期。 如果您按照您寫的方式需要它:“Hi-World Java”,那么您需要自己的邏輯,如此處的其他一些答案中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM