首页 > 解决方案 > 如何检查字母及其在字符串中的位置?

问题描述

我正在使用 C# 统一制作一个刽子手游戏。

我正在使用此代码来检查单词中的字母:

string s = "Hello World";

foreach(char o in s)
{
    Debug.Log(o);
}

我需要检查所有字母并检查是否有玩家输入的字母,如我的示例中那样o

然后我需要用*我检查的字母替换由星星代表的未知字母。

我必须跟踪这些字母的位置,以便以后替换它们。

有什么方法可以跟踪字母的位置吗?

标签: c#stringreplacechar

解决方案


C# 中的字符串是不可变的。所以你必须创建一个包含新猜测字母的新字符串。如果您是编程新手:将您的代码划分为执行特定任务的函数。

一个可能的解决方案如下:

using System;
                    
public class Program
{
    public static void Main()
    {
        string answer = "Hello";
        // The length of the string with stars has to be the same as the answer.
        string newWord = ReplaceLetter('e', "*****", answer);
        Console.WriteLine(newWord);                             // *e***
        newWord = ReplaceLetter('x', newWord, answer);
        Console.WriteLine(newWord);                             // *e***
        newWord = ReplaceLetter('H', newWord, answer);
        Console.WriteLine(newWord);                             // He***    
        newWord = ReplaceLetter('l', newWord, answer);
        Console.WriteLine(newWord);                             // Hell*                
    }
    
    public static string ReplaceLetter(char letter, string word, string answer)
    {
        // Avoid hardcoded literals multiple times in your logic, it's better to define a constant.
        const char unknownChar = '*';
        string result = "";
        for(int i = 0; i < word.Length; i++)
        {
            // Already solved?
            if (word[i] != unknownChar) { result = result + word[i]; }
            // Player guessed right.
            else if (answer[i] == letter) { result = result + answer[i]; }
            else result = result + unknownChar;
        }
        return result;
    }
}

推荐阅读