C#Hangman IndexOf Loop

时间:2014-02-27 18:14:39

标签: c# indexof

我是C#的初学者,我正在尝试制作一个“刽子手”游戏。当玩家猜出一封信时,我陷入了困境。

如果单词例如是DATA,则应用程序仅获取DATA中的第一个A. 我知道我必须循环这个词以获得所有的A,但是我觉得它很有效!

这是myGuess方法的代码:

public void myGuess(String letter)
{
        int plats = 0;

        string wordToGuess = label4.Text;

        plats = wordToGuess.IndexOf(letter);

        string wordToShow = label5.Text;
        //ersätt "_" med bokstaven på alla positioner bokstaven dyker upp

        wordToShow = wordToShow.Substring(0, wordToGuess.IndexOf(letter)) + letter +
                     wordToShow.Substring(plats + 1, wordToShow.Length - (plats + 1));

        label5.Text = wordToShow;  
}

我一直试图谷歌它,但因为我是一个初学者,我不明白 人们给出的建议。希望这是一种循环使用IndexOf多个字母的方法?

4 个答案:

答案 0 :(得分:1)

IndexOf返回字符串中第一个字符实例的索引。你可以使用子字符串来操纵你的字符串,但是你要使它比你需要的更复杂。相反,您可以使用for循环遍历String中的每个字符:

for (int i = 0; i < wordToGuess.Length; i++ )
{
    if (WordToGuess[i] == letter)
    {
         //Update the correctly guessed letters, (using value of i to determine which letter to make visible.)
    }
}
label5.Text = wordToShow;

答案 1 :(得分:1)

您可以使用:

label4(wordToGuess): DATA
label5(wordToShow):  ****

当你调用myGuess('A')

label4(wordToGuess): DATA
label5(wordToShow):  *A*A

当你打电话给myGuess('T')

label4(wordToGuess): DATA
label5(wordToShow):  *ATA

...

public void myGuess(char letter)
    {
        string wordToGuess = label4.Text;
        string wordToShow = label5.Text;

        if (wordToShow.Length == 0)
        {
            for (int i = 0; i < wordToGuess.Length; i++)
                wordToShow += "*";
        }

        for (int i = 0; i < wordToGuess.Length; i++)
        {
            if (wordToGuess[i] == letter || wordToGuess[i] == wordToShow[i])
                wordToShow = wordToShow.Remove(i,1).Insert(i, Char.ToString(letter));
        }

        label5.Text = wordToShow;
    }

答案 2 :(得分:1)

这是一个很长的解决方案,可能过于通用了。

List<int> findIndexes(string myStr, char letter)
{
    var foundIndexes = new List<int>();
    for (int i = 0; i < myStr.Length; i++)
    {
        if (myStr[i] == letter)
        foundIndexes.Add(i);
    }
    return foundIndexes;
}
string ReplaceIndex(string s, int index, char letter){
    return s.Substring(0, index ) 
    + letter 
    + s.Substring(index + 1, s.Length - (index + 1));
}
void Main()
{
    string s= "data";
    string wordToShow = "____";
    var letter = 'a';
    var indexes = findIndexes(s, letter);
    foreach (var index in indexes)
    {
        wordToShow = ReplaceIndex(wordToShow, index, letter);
    }
    Console.WriteLine (wordToShow);
}

答案 3 :(得分:0)

一个简单的for循环应该处理它。

for (int i = 0; i < wordToGuess.Length; i++)
{
    if (wordToGuess[i].ToString().Equals(letter.ToString(), System.StringComparison.InvariantCultureIgnoreCase))
    {
        wordToShow = string.Format("{0}{1}{2}", wordToShow.Substring(0, i), letter, wordToShow.Substring(i, wordToShow.Length - (i + 1)));
    }
}

这是一个小提琴:http://dotnetfiddle.net/UATeVJ