How to replace Characters in a String with Characters from another?

Weird title, but not sure how else to explain it.
Basically, for a game of hangman, I have two strings. One of the strings is the randomly generated word, and the other is the word but with dashes instead of characters (e.g ‘the’ would be ‘—’)

Is there any way to easily replace one of the dashes with the appropriate letter if guessed correctly?(e.g if one guessed ‘t’, the first dash needs to be replaced with a ‘t’ to make “t–” I am guessing it requires stringBuilder, but I am not sure how to go about it.

Thanks in advance,

MrFodds

string myString = “Hello World”;
string resultString = “_____ _____”;
string test = “o”;
int i = myString.IndexOf (test);
while (i != -1) {
resultString = resultString.Substring (0, i) + “o” + resultString.Substring (i + 1);
myString = myString.Substring (0, i) + “" + myString.Substring (i + 1);
i = myString.IndexOf (test);
}
Debug.Log (myString); // "Hell
W_rld”
Debug.Log (resultString); // “__o o

You can avoid to use StringBuilder by just replacing a char in a string. You can use a loop to go trough the whole random word and see if there is any char equal to the input character the player want to use. Just remember that strings are arrays themself of characters, but just read only. Here a little script I put up toghter to explain better:

using UnityEngine;

public class Hangman : MonoBehaviour {

	public string randomWord;			//The random generated word (not so random for this script)
	private string hiddenWord;			//The hidden word that need to be guessed
	public string inputChar;			//The char to input to discover the word

	// Use this for initialization
	void Start () {
		for (int i = 0; i < randomWord.Length; i++)
			hiddenWord += "-";
	}

	//Check if the random word contain any character typed in the input text field
	void CheckChar () {
		int charIndex = 0;

		//Search the array of chars of the random string
		for (int i = 0; i < randomWord.Length; i++) {
			//Conversion to string is needed for a direct comparing
			if (randomWord*.ToString() == inputChar) {*
  •  		//Set the index for each loop pass. Used to set which char need to be replaced*
    
  •  		charIndex = i;*
    
  •  		//Remove character that has been found from*
    
  •  		hiddenWord = hiddenWord.Remove(charIndex,1);*
    
  •  		//Assign the correct char to the full result string*
    
  •  		hiddenWord = hiddenWord.Insert(charIndex,inputChar);*
    
  •  		Debug.Log ("Correct Char: " + hiddenWord[charIndex]);	*
    
  •  	}*
    
  •  }*
    
  • }*

  • // Update is called once per frame*

  • void OnGUI () {*

  •  GUI.Label (new Rect (10, 10, 200, 100), hiddenWord + "    (Correct Word: " + randomWord + ")");*
    
  •  //The character the player can input (limited to one char only)*
    
  •  inputChar = GUI.TextField (new Rect (10, 40, 200, 20), inputChar, 1);*
    
  •  if(GUI.Button (new Rect(220,40,80,20), "Submit")) {*
    
  •  	//Prevent char to be sent if null*
    
  •  	if(!string.IsNullOrEmpty(inputChar))*
    
  •  		CheckChar();*
    
  •  	//Reset input char to empty*
    
  •  	inputChar = "";*
    
  •  }*
    
  • }*
    }
    There is no random word generation but if I understood correctly, you got that covered. By the way as you can see on Start I make sure that the hidden word is the same length of the random generated one, and apply all char as “-” (you cna use whatever you wish).
    Then on the OnGUI code there is just an input field limited to one char. After you press Submit it goes trough a loop using the random generated word itself as reference. Notice that on the comparing char part I use ToString(), this is because a string array return a char, so for a direct comparison I need to cast back to string, probably there are more elegant ways to do this.
    If the loop find a corresponding char to the input one all chars of the same letter will be changed on the hidden string, so if you have 3 “c” in the random word, all 3 of them will be discovered.
    The only downside to this, is that is case sensitive, so A != a for example. Hope this helps.

Hi,
I started writing a reply to this before I saw Neurological’s reply… but more answers are better than none :stuck_out_tongue:
Both are similar approaches and whichever you prefer will depend more on your coding style.
It’s all pretty self-explanatory. Like Neurological mentioned, strings are just an array of chars which is why you can access a char by index like in the FindLetter method. The only major difference is that it’s not case sensitive, which you can see also in the FindLetter method.
Have fun :slight_smile:

using UnityEngine;
using System.Collections;
using System.Text;

public class Hangman : MonoBehaviour 
{
	public class HangmanWord
	{
		public  string word { get; private set; }
		public  string revealedLetters { get; private set; }
		
		public HangmanWord(string newWord) 
		{
			word = newWord;
			revealedLetters = new string('-', word.Length);
		}
				
		public void FindLetter(string letter) 
		{
			for(int index=0; index<word.Length; index++) 
			{
				if(word.ToLowerInvariant()[index] == letter.ToLowerInvariant()[0]) {
					RevealAt(index);
				}
			}
			
   			if(revealedLetters == word) {
				Debug.Log("You won!");		
			}
		}	
				
		private void RevealAt(int index)
		{
			char[] letters = revealedLetters.ToCharArray();
			letters[index] = word[index];
				
			revealedLetters = new string(letters);
		}
	}
	
	
	private HangmanWord myHangmanWord;
	private string      letterPressed = string.Empty;
		
	private void Start() 
	{
		// Fill in the string with your random word generation..
		myHangmanWord = new HangmanWord("Hello");
	}
		
	private void OnGUI() 
	{
		// Simple GUI stuff..
		// Just displays the letters and takes player input..
				
		GUI.Label(new Rect(10, 10, 200, 100), myHangmanWord.revealedLetters);
		
		GUI.Label(new Rect(10, 30, 200, 100), "Enter a letter:");
		letterPressed = GUI.TextField(new Rect(10, 60, 40, 20), letterPressed, 1);
		
		if(!string.IsNullOrEmpty(letterPressed)) {
			myHangmanWord.FindLetter(letterPressed);
		}
		
		letterPressed = string.Empty;
	}
}