Replace Space to Hyphen
I am trying to replace a space character into a hyphen I have in my string.
String replaceText = "AT AT";
replaceText.replace(' ', '-');
but when I do this, I cannot seem to replace the character. I tried the replaceAll()
method and it doesn't work either.
++++++Answer+++++++
sorry my mistake.. the result of late night programming :(
thanks for the answer i cant probably answer all so i will check the first answer
replaceText = replaceText.replace(开发者_开发知识库' ', '-');
replaceText = replaceText.replace(' ', '-');
Strings are immutable, they cannot be changed after creation. All methods that somehow modify a string will return a new string with the modifications incorporated.
Strings are immutable.
You need to save the value returned by replace()
. If you want to replace more than one occurrence, use replaceAll()
.
String replaceText = "AT AT";
replaceText = replaceText.replaceAll(" ", "-");
As @Mark Peters points out in the comments, replace(Char, Char)
is sufficient (and faster) for replacing all occurrences.
String replaceText = "AT AT";
replaceText = replaceText.replace(' ', '-');
In case this fact bothers you: immutability is a Good Thing
.
The replace
and replaceAll
methods return a String with the replaced result. Are you using the returned value, or expecting the replaceText
String to change? If it's the latter, you won't see the change, because Strings are immutable.
String replaceText = "AT AT";
String replaced = replaceText.replace(' ', '-');
// replaced will be "AT-AT", but replaceText will NOT change
The replace method returns a String, so you need to re-assign your string variable i.e.
String replaceText = "AT AT";
replaceText = replaceText.replace(' ', '-');
Strings are immutable. You need to use the return value from replace:
replaceText = replaceText.replace(' ', '-');
/*You can use below method pass your String parameter and get result as String spaces replaced with hyphen*/
private static String replaceSpaceWithHypn(String str) {
if (str != null && str.trim().length() > 0) {
str = str.toLowerCase();
String patternStr = "\\s+";
String replaceStr = "-";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll(replaceStr);
patternStr = "\\s";
replaceStr = "-";
pattern = Pattern.compile(patternStr);
matcher = pattern.matcher(str);
str = matcher.replaceAll(replaceStr);
}
return str;
}
If you are replacing many strings you want to consider using StringBuilder for performance.
String replaceText = "AT AT";
StringBuilder sb = new StringBuilder(replaceText);
sb.Replace(' ', '-');
精彩评论