What I want to do is replace one character for another in a string. More specifically what I need is as follows.
I have this code: char userChar = 'X'
and I have String name = "Annette"
I want to replace the first n
in "Annette" with userChar
. So using the .replace()
method is not an option since it would replace all the n
s. One thing that I can think of is using the substring
method and cutting out all the text besides for the first "n" and then concatenating those two substrings back together, and then use a StringBuilder
and an insert
method to insert the 'X' in the n
's place. However this seems a little bit crazy. I was wondering if anybody had any other ideas?
Asked
Active
Viewed 1,997 times
-1

Jacob
- 524
- 5
- 18
-
Why not use a loop that returns after the first replacement? – Adrian M. Dec 15 '15 at 00:34
-
Okay, apparently I needed to be more specific with my question. What do I do if the character that needs replacing isn't the first character? I need a method similar to `userName.replace(the position of the letter that needs replacing, the character to replace it by)` – Jacob Dec 15 '15 at 00:44
-
Do you know position of character you want to replace or do you need to calculate it first? – Pshemo Dec 15 '15 at 00:50
-
@Pshemo It's a hangman game. I originally display a secret phrase as `** ****` for example. And every time the player guesses a letter, the asterisk gets replaced by that letter. – Jacob Dec 15 '15 at 01:11
-
Then you can simply use `char[]`. Notice that you can use `System.out.println(charArray)` to print its content. You will need two arrays, one which will store correct text, and other which will be used as mask which you will print. Simply replace all characters in mask to `*` or if they are characters. Then if player will want to check some character iterate over array with correct text, and when it finds same character as player provided replace `*` back to that character in mask. – Pshemo Dec 15 '15 at 01:27
3 Answers
4
You can use String#replaceFirst(target,replacement)
.
But be careful since that method is using regex syntax so you can't easily replace characters like +
*
and other metacharacters. To solve this problem you can use methods which will add escaping for you like
Pattern.quote
fortarget
- and
MatcherMatcher.quoteReplacement
forreplacement
.

Pshemo
- 122,468
- 25
- 185
- 269
1
This link can help: Replace a character at a specific index in a string?
Peter Ivanov gave this answer.
Just to summarize, try StringBuilder
as you did, but using a different method.
StringBuilder name = new StringBuilder("Annette");
name.setCharAt(1, username);
I hope this works for you!