28

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,

1

8 Answers 8

46

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", "");
Sign up to request clarification or add additional context in comments.

1 Comment

replace does not accept regular expressions, therefore you should not escape the .. replaceAll does accept regular expressions, however.
11

Can't you use

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

And what Eric said, ofcourse.

2 Comments

This assumes that he expects .xml to be at the end of the string (probable, though not stated).
That's why I stated the question ^.^ But, ofcourse, Eric's answer seems prettier.
3

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

Comments

2

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

Comments

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

Comments

1

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

3 Comments

8 years later..... also StringUtils is from Apache? Not native Java... should probably specify that
Added doc link. It should be implied, native doesn't contain any Util. This is a safer, more complete answer than any of the others
Wasn't saying it wasn't implied... I was saying that it was not as helpful because you didn't specify where to find the function... but the doc link definitely clears that up 👍
0

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

Comments

0

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

Comments