[java] 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,

This question is related to java string

The answer is


String id = id.substring(0,id.length()-4)

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 £:


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);

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


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", "");.


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