如何检查字母及其在字符串中的位置?
How to check for letters and their position in a string?
我正在使用 C# 统一制作刽子手游戏。
我正在使用此代码检查单词中的字母:
string s = "Hello World";
foreach(char o in s)
{
Debug.Log(o);
}
我需要遍历所有字母并检查是否有玩家在我的示例中输入的字母 o
。
然后我需要用我检查的字母替换星号代表的未知字母*
。
我必须跟踪字母的位置,以便稍后替换它们。
有什么方法可以跟踪字母的位置吗?
改为使用 for
循环:
for (int i = 0; i < s.Length; i++)
{
char o = s[i];
Debug.Log(o);
}
字符串有一个 indexer 可用于获取给定索引处的字符。
通过使用 for
循环,您可以访问每次迭代的索引 i
。
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;
}
}
我正在使用 C# 统一制作刽子手游戏。
我正在使用此代码检查单词中的字母:
string s = "Hello World";
foreach(char o in s)
{
Debug.Log(o);
}
我需要遍历所有字母并检查是否有玩家在我的示例中输入的字母 o
。
然后我需要用我检查的字母替换星号代表的未知字母*
。
我必须跟踪字母的位置,以便稍后替换它们。
有什么方法可以跟踪字母的位置吗?
改为使用 for
循环:
for (int i = 0; i < s.Length; i++)
{
char o = s[i];
Debug.Log(o);
}
字符串有一个 indexer 可用于获取给定索引处的字符。
通过使用 for
循环,您可以访问每次迭代的索引 i
。
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;
}
}