[英]Remove characters from a String in Java
I am trying to remove the .xml
part of a file name with the following code:我正在尝试使用以下代码删除文件名的
.xml
部分:
String id = fileR.getName();
id.replace(".xml", "");
idList.add(id);
The problem is that it is not removing it and I have no clue why it won't remove the target text.问题是它没有删除它,我不知道为什么它不会删除目标文本。
EDIT : Actually I realize that the replace function won't find the .xml
, so I guess the question is, how do I get rid of those last 4 characters?编辑:实际上我意识到替换函数不会找到
.xml
,所以我想问题是,我如何摆脱最后 4 个字符?
Here is the string that is being passed in:这是传入的字符串:
0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e.xml
Thanks,谢谢,
Strings in java are immutable. java中的字符串是不可变的。 That means you need to create a new string or overwrite your old string to achieve the desired affect:
这意味着您需要创建一个新字符串或覆盖旧字符串以实现所需的效果:
id = id.replace(".xml", "");
Can't you use你不能用吗
id = id.substring(0, id.length()-4);
And what Eric said, ofcourse.当然,还有埃里克所说的。
Strings are immutable, so when you manipulate them you need to assign the result to a string:字符串是不可变的,因此当您操作它们时,您需要将结果分配给一个字符串:
String id = fileR.getName();
id = id.replace(".xml", ""); // this is the key line
idList.add(id);
String
s are immutable. String
是不可变的。 Therefore String.replace()
does not modify id
, it returns a new String
with the appropriate value.因此
String.replace()
不会修改id
,它返回一个具有适当值的新String
。 Therefore you want to use id = id.replace(".xml", "");
因此你想使用
id = id.replace(".xml", "");
. .
String id = id.substring(0,id.length()-4)
This will safely remove only if token is at end of string.只有当令牌位于字符串末尾时,这才会安全地删除。
StringUtils.removeEnd(string, ".xml");
Apache StringUtils functions are null-, empty-, and no match- safe
Apache StringUtils函数是空、空和无匹配安全的
Kotlin has a built-in function for this, removeSuffix
( Documentation ) Kotlin 有一个内置函数,
removeSuffix
( 文档)
var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"
If the suffix does not exist in the string, it just returns the original如果字符串中不存在后缀,则只返回原来的
var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"
You can also check out removePrefix
and removeSurrounding
which are similar您还可以查看类似的
removePrefix
和removeSurrounding
Java strings are immutable. Java 字符串是不可变的。 But you has many options:
但是你有很多选择:
You can use:您可以使用:
The StringBuilder class instead, so you can remove everything you want and control your string.而是 StringBuilder 类,因此您可以删除您想要的所有内容并控制您的字符串。
The replace method.替换方法。
And you can actually use a loop £:你实际上可以使用循环£:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.