如何检查一个字符串变量中的每个字母? 我正在尝试制作一个可以将句子翻译为1和0的程序。 看看下面的代码,这就是我现在做了多少。我可以从文本文件中读取值,并只写出一个字母的值。我想知道如何编写我的代码,以便能够检查句子中的每个字母。![在此输入图像描述] [1]
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string[] lines = File.ReadAllLines("Values.txt");
for (int i = 0; i < 4; i++)
{
string value = lines[i].Substring(4);
string identifier = lines[i].Substring(0, 1);
dictionary.Add(identifier, value);
}
string sentence = Console.ReadLine();
if (sentence == "A")
{
Console.WriteLine(dictionary[sentence]);
}
else if (sentence == "B")
{
Console.WriteLine(dictionary[sentence]);
}
Console.ReadKey();
答案 0 :(得分:0)
如果你想在你的句子变量中迭代字符,你可以使用foreach:
foreach (var item in sentence)
{
....
}
在此示例中,item是char类型的变量。您可以调用ToString()方法将其转换为字符串。
答案 1 :(得分:0)
由于您将此标记为C#,所以您真正需要做的是从字符串中读取数据,因为C#允许索引
String wordzyo = "ABCDEF";
char aLeter = wordzyo[0]; // read "A" into CHAR "aLeter"
如果这是Java而不是C#,你会使用&#34; aLeter.charAt(0);&#34;
不知道为什么要问这个?它曾被问过一百次......