c# - 如何检查字母及其在字符串中的位置?
问题描述
我正在使用 C# 统一制作一个刽子手游戏。
我正在使用此代码来检查单词中的字母:
string s = "Hello World";
foreach(char o in s)
{
Debug.Log(o);
}
我需要检查所有字母并检查是否有玩家输入的字母,如我的示例中那样o
。
然后我需要用*
我检查的字母替换由星星代表的未知字母。
我必须跟踪这些字母的位置,以便以后替换它们。
有什么方法可以跟踪字母的位置吗?
解决方案
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;
}
}
推荐阅读
- angular - CSRF 实施不适用于 OAM
- python - Discord Python 异步事件循环已关闭
- python - 使用 Python 遍历嵌套列表
- php - CakePHP - 在 null 上调用成员函数 allow()
- excel - IF 函数,条件乘法
- protractor - 如何使用量角器/黄瓜/打字稿在测试框架中以无头模式截屏
- embedded-linux - Yocto PREMIRROR/SOURCE_MIRROR_URL 可能带有 url 参数(SAS_TOKEN)?
- json - 从 jq 生成表格输出
- javascript - 正则表达式接受任何值,但在 javascript 中的最大长度为 200
- android - 如何动态强制小部件向右移动?