[英]Removing/ignoring all the punctuation in a given string
我試圖從我的字符串中刪除每個標點符號:到目前為止,我已完成以下操作:
String line = "there's, isn't";
line.replaceAll("\\p{Punct}", "")
然而,這不能改變“有”到“theres”或“is not”到“isnt”。
我認為\\ p {Punct}包括每個標點符號,包括“'”(如api中所示)但這不起作用。 有人可以幫忙嗎?
提前致謝。
PS:預期結果是: theres isnt
字符串在Java中是不可變的。 字符串方法不會更改字符串,而是返回字符串的修改副本,因此您需要將結果分配回變量:
String line = "there's, isn't";
line = line.replaceAll("\\p{Punct}", "");
System.out.println(line); // theres isnt
正如之前的回答所說,字符串是不可變的,一旦創建,你就無法真正改變它。 所以一旦你編碼像String line = "there's, isn't";
將創建字符串對象"there's, isn't"
並為其分配line
變量。 Java沒有指針的概念,但你可以把它想象成指向給定字符串的line
變量"there's, isn't"
。 現在你的下一行line.replaceAll("\\\\p{Punct}", "")
返回一個新創建的字符串對象。 你可以將它分配給另一個變量,比如line_cleared=line.replaceAll("\\\\p{Punct}", ""
並打印出來:所以這里是完全更新的代碼:
String line = "there's, isn't";
line_cleared= line.replaceAll("\\p{Punct}", "");
System.out.println(line_cleared);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.