简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM