【问题标题】:How to check for letters and their position in a string?如何检查字母及其在字符串中的位置?
【发布时间】:2021-10-11 11:42:28
【问题描述】:

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

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

string s = "Hello World";

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

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

然后我需要将星号*代表的未知字母替换为我检查过的字母。

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

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

【问题讨论】:

  • 字符串是字符数组,所以 s[0] 包含字母 'H' 而 s[1] 包含字母 'e'等等。你能解释一下为什么你需要知道字符串(数组)中的字母位置(索引)吗?
  • @Steve 从技术上讲,字符串不是字符数组,但它确实允许通过索引访问字符。
  • @JohnathanBarclay 字符串 字符数组,即连续的内存单元块,例如带有货车的火车(现在使用 unicode 和 .NET 为 2 个字节)。无论处理器的世代和类型如何,我们使用集成电路存储器技术的硅和晶体管计算机一直都是这种情况,而且永远都是这样。但是谁知道量子计算机或 DNA 计算机,例如水晶内存……出于性能原因,字符串在技术上存储在任何旧的和现代的真实计算机上的 .NET 中的 char 数组中,就像在 C 中一样。
  • @JohnathanBarclay 当然,String 类是底层 char 数组的高级包装器。也许您的意思是 String 不是 char[] 原样。确实。不假。 Is string actually an array of chars or does it just have an indexer?How are String and Char types stored in memory in .NET?C# How to store a stringHow string is stored in C#

标签: c# string replace char


【解决方案1】:

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;
    }
}

【讨论】:

  • 谢谢,这确实有很大帮助。
【解决方案2】:

改用for 循环:

for (int i = 0; i < s.Length; i++)
{
    char o = s[i];
    Debug.Log(o);
}

String 有一个indexer,可用于获取给定索引处的字符。

通过使用for 循环,您可以访问每次迭代的索引i

【讨论】:

  • 对不起,我不是很擅长编程,怎么能用那个索引把未知的字母替换成字母“o”
猜你喜欢
  • 1970-01-01
  • 2011-08-16
  • 2011-12-24
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多