Java String replace not working [duplicate]
String is immutable, which means that the html reference doesn’t change, rather the replace method returns a new String object that you have to assign.
html = html.replace(delimiter + entry.getKey()+ delimiter, entry.getValue());
Just tested, but not seccessfully.. The new strings just wont be replaced. —Edit: went wonderfull, after I have adjusted my delimiter.
String longitudeString=siteResult.getString(«longitude»).toString().replaceAll(» «,»»); this is a jdbc example. there are not working «replace or replaceAll»
@withoutOne Then you have a different problem. Your code will result in longitudeString to not having any spaces in it.
The replace method returns its result, which you’re discarding.
You don’t need to escape * character. Difference between replace and replaceAll is that replace escapes any regex metacharacters for us automatically:
as said you are discarding the results and replace doesn’t take a regex only a literal char sequence to be replaced so you don’t need to escape in the delimiter
but replaceAll and replaceFirst do take a regex string (bad design that)
and as an aside it’s advisable to use Patter.quote(String) and Matcher.quoteReplacement(String) to ensure no weird things are happening when using regex (it’s a bit easier and ensures there’s no error in escaping the chars)
here’s for when only one occurrence must be replaced
String delimiter = "**"; String html = " **USERNAME** AND **PASSWORD**"; Map mp = new HashMap(); mp.put("USERNAME", "User A"); mp.put("PASSWORD", "B"); for (Map.Entry entry : mp.entrySet())
and here’s for when multiple occurrences must be replaced
String delimiter = "**";//unescaped because I'm handling that in my replace String html = " **USERNAME** AND **PASSWORD**"; Map mp = new HashMap(); mp.put("USERNAME", "User A"); mp.put("PASSWORD", "B"); for (Map.Entry entry : mp.entrySet())
String replace method is not replacing characters
I have a sentence that is passed in as a string and I am doing a replace on the word «and» and I want to replace it with » «. And it’s not replacing the word «and» with white space. Below is an example of my logic. And when I debug this the logic does fall into the sentence.replace.
String sentence = "Define, Measure, Analyze, Design and Verify" if (sentence.contains("and"))
5 Answers 5
And when I debug this the logic does fall into the sentence.replace.
Yes, and then you discard the return value.
Strings in Java are immutable — when you call replace , it doesn’t change the contents of the existing string — it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
This applies to all the methods in String ( substring , toLowerCase etc). None of them change the contents of the string.
Note that you don’t really need to do this in a condition — after all, if the sentence doesn’t contain «and» , it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify"; sentence = sentence.replace("and", " ");
I’ve got to call you out on answering a dup instead of voting to close. This problem has been asked & answered so many times before — what’s the deal, Jon?
@MattBall: As so often happens, I find it quicker to give a good, complete answer than to find a duplicate which also has a good answer. I believe (somewhat egotistically, admittedly) that my answer here is better than the accepted one in the duplicate you found, which doesn’t even really make technical sense. («You need to make your string actually equal the changes you make to the string» — what?) Additionally, I wanted to point out the aspect about not needing to check for containment first.
Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:
As an aside, note that I’ve removed the contains() check, as it is an unnecessary call here. If it didn’t contain it, the replace will just fail to make any replacements. You’d only want that contains method if what you’re replacing was different than the actual condition you’re checking.
ReplaceAll and " doesn’t replace
Can anyone point me out how the first if works and the second doesn’t? I’m puzzled why the second if-clause isn’t working. I’d like to get a hint, thanks.
String msg = o.getTweet(); if (msg.indexOf("&") > 0) < msg = msg.replaceAll("&", "&");// vervangt & door & >if (msg.indexOf(""") > 0) < msg = msg.replaceAll(""", "aa"); //vervangt " door " >
2 Answers 2
Because ZERO is a very valid index. Try this out,
String msg = o.getTweet(); if (msg.indexOf("&") != -1) < msg = msg.replaceAll("&", "&");// vervangt & door & >if (msg.indexOf(""") != -1) < msg = msg.replaceAll(""", "aa"); //vervangt " door " >
Explanation:
The documentation of String.indexOf(String str) explains that, «if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned.» — [link to docs]
This can be done as simple as below, as OpenSauce pointed out here.
Useful links:
This works perfectly! Could you give me a little more explanation why -1 is better than zero? Thank you in advance!
@Hannelore: When your string begins with «"» , indexOf will return 0 because counting starts at 0.
@Hannelore As Adeel says, 0 is a valid index — it means the first character of the string. So your code was buggy because it considered 0 to mean «not found» — but it does not mean that in this case.
You don’t need to check the substring exists, the replace and replaceAll methods are no-ops if the substring is not found. Since you’re not looking for regexes, you can also use replace instead of replaceAll — it will be somewhat more efficient, and won’t surprise you if you also want to check for other strings which happen to contain regex special chars.
note that replace does indeed replace all matches, like you want. The difference between replace and replaceAll is whether the arg is interpreted as a regex or not.
replaceAll does not replace string [duplicate]
I want the text «REPLACEME» to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery() < String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="; deserializeQuotes(); StringBuffer symbols = new StringBuffer(); for(int i = 0; i < quotes.size();i++)< if(i == (quotes.size()-1)) symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote else symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C"); >System.out.println("***SYMBOLS***" + symbols.toString()); query.replaceAll("REPLACEME", symbols.toString()); return query; >
3 Answers 3
query.replaceAll("REPLACEME", symbols.toString());
query = query.replaceAll("REPLACEME", symbols.toString());
Strings in Java are designed to be immutable.
That is why replaceAll() can’t replace the characters in the current string, so it must return a new string with the characters replaced.
Also if you want to simply replace literals and don’t need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like * , + , [ , ] and others.
Java String.replace/replaceAll not working
So, I’m trying to parse a String input in Java that contains (opening) square brackets. I have str.replace(«\\[«, «») , but this does absolutely nothing. I’ve tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it’s been that way for over a year and hasn’t caused me any issues like this before. Any idea what I might be doing wrong here?
4 Answers 4
Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:
For the normal replace method, you don’t need to escape the bracket:
Yes, the clue is in the return type, uchuujin: why would replaceAll return String if it modified the String in place; shouldn’t it be void ?
public String replaceAll(String regex, String replacement)
As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like «(«, «)» etc (with «\«) if these exists in your replacement text which is to be replaced out of the string. For example :
String oldString = "This is (stringTobeReplaced) with brackets."; String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", ""); System.out.println(newString); // will output "This is with brackets."
Another way of doing this is to use Pattern.quote(«str») :
String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");
This will consider the string as literal to be replaced.