Reputation: 15389
I know of no easy way to do this. Suppose I have the following string-
"abcdefgh"
I want to get a string by replacing the third character 'c' with 'x'.
The long way out is this -
s1 = substring before third character = "ab" in this case
s2 = new character = "x" in this case
s3 = substring after third character = "defgh" in this case
finalString = s1 + s2 + s3
Is there a simpler way? There should be some function like
public String replace(int pos, char replacement)
Upvotes: 0
Views: 123
Reputation: 8818
How about:
String crap = "crap";
String replaced = crap.replace(crap.charAt(index), newchar);
but this will replace all instances of that character
Upvotes: -1
Reputation: 4443
Since every String is basically just a char[] anyway, you could just grab it and manipulate the individual chars that way.
Upvotes: 1
Reputation: 34
Try the String.replace(Char oldChar, Char newChar)
method or use a StringBuilder
Upvotes: -1
Reputation: 3
String yourString = "abcdef"
String newString = yourString.replaceAll("c" , "x");
System.out.println("This is the replaced String: " + newString);
This is the replaced String: abxdef
Upvotes: -2
Reputation: 36476
You can convert the String
to a char[]
and then replace the character. Then convert the char[]
back to a String
.
String s = "asdf";
char[] arr = s.toCharArray();
arr[0] = 'b';
s = new String(arr);
Upvotes: 3
Reputation: 359846
StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();
Upvotes: 5