CodeBlue
CodeBlue

Reputation: 15389

Is there a simple way to replace a character at any arbitrary position in a string in Java (and get new String)?

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

Answers (8)

Phillip Schmidt
Phillip Schmidt

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

John Kane
John Kane

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

oli
oli

Reputation: 34

Try the String.replace(Char oldChar, Char newChar) method or use a StringBuilder

Upvotes: -1

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

tskuzzy
tskuzzy

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

Matt Ball
Matt Ball

Reputation: 359846

Use StringBuilder#replace().

StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();

http://ideone.com/Tg5ut

Upvotes: 5

Mike
Mike

Reputation: 3311

Try using a StringBuilder instead StringBuilder Java Page

Upvotes: 1

bmargulies
bmargulies

Reputation: 100051

No. There is no simpler way than to concatenate the pieces.

Upvotes: 2

Related Questions