I've been trying to create a Hangman game in Java, and I have a string that looks like "_____" for a certain number of letters that they are supposed to represent. How would I replace just one of those, rather than all? I've heard that you can't replace an underscore with the String.replace method, but I couldn't figure it out with Pattern and Matcher. Here's the code:

String b = "____";
char c = b.charAt(0); 
b = b.replace(c, 'a');
System.out.println(b);

Please respond as soon as you can! Thanks!

Recommended Answers

All 2 Replies

what you are doing here is copying a character from b into c and then playing with that c. What you should do instead is use substrings:

String b = "_____";
b = b.substring(0,3) + 'a' + b.substring(5);
System.out.println(b);

This should do it. You can modify the substring start and end index according to the program requirements.

Member Avatar for hfx642

You have two strings which are both the same length.
One with the underscores. And one with your word.
Search the second string to find the index of occurance of the letter.
The letter "a" is at index 2. (zero based, of course)

String Unders = "_____";
String Word  = "board";
int Index = Word.indexOf ("a");
Unders = Unders.substring (0, Index) + Word.substring (Index, Index + 1) + Unders.substring (Index + 1);

Your result would be "__a__"
Loop for each letter entered until no underscores are left.

commented: Nice +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.