[英]Remove characters from a String in Java
我正在嘗試使用以下代碼刪除文件名的.xml
部分:
String id = fileR.getName();
id.replace(".xml", "");
idList.add(id);
問題是它沒有刪除它,我不知道為什么它不會刪除目標文本。
編輯:實際上我意識到替換函數不會找到.xml
,所以我想問題是,我如何擺脫最后 4 個字符?
這是傳入的字符串:
0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e.xml
謝謝,
java中的字符串是不可變的。 這意味着您需要創建一個新字符串或覆蓋舊字符串以實現所需的效果:
id = id.replace(".xml", "");
你不能用嗎
id = id.substring(0, id.length()-4);
當然,還有埃里克所說的。
字符串是不可變的,因此當您操作它們時,您需要將結果分配給一個字符串:
String id = fileR.getName();
id = id.replace(".xml", ""); // this is the key line
idList.add(id);
String
是不可變的。 因此String.replace()
不會修改id
,它返回一個具有適當值的新String
。 因此你想使用id = id.replace(".xml", "");
.
String id = id.substring(0,id.length()-4)
Kotlin 有一個內置函數, removeSuffix
( 文檔)
var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"
如果字符串中不存在后綴,則只返回原來的
var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"
您還可以查看類似的removePrefix
和removeSurrounding
Java 字符串是不可變的。 但是你有很多選擇:
您可以使用:
而是 StringBuilder 類,因此您可以刪除您想要的所有內容並控制您的字符串。
替換方法。
你實際上可以使用循環£:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.