开发者

Remove characters from a String in Java

I am trying to remove the .xml part of a file name with the following code:

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?

Here is the string that is being passed in:

0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e.xml

Thanks,


Strings in java are immutable. 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);


Strings are immutable. Therefore String.replace() does not modify id, it returns a new String with the appropriate value. Therefore you want to use 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


Kotlin Solution

Kotlin has a built-in function for this, removeSuffix (Documentation)

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


Java strings are immutable. But you has many options:

You can use:

The StringBuilder class instead, so you can remove everything you want and control your string.

The replace method.

And you can actually use a loop £:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜