I am trying to replace a space character into a hyphen I have in my string.
String replaceText = \"AT AT\";
replaceText.replace(\' \', \'-\');
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
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(' ', '-');
/*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;
}
Strings are immutable. You need to use the return value from replace:
replaceText = replaceText.replace(' ', '-');
The replace method returns a String, so you need to re-assign your string variable i.e.
String replaceText = "AT AT";
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.