简体   繁体   English

如何在 C# 的字符串中找到某个字母?

[英]How can I find a certain letter in a String in C#?

How can I search a certain letter (char) in a String?如何在字符串中搜索某个字母(字符)?

I have to code a little riddle.我必须编写一个小谜语。 You basicalley have to guess the right letters of an unknown word.您基本上必须猜出一个未知单词的正确字母。 Only the first letter is shown.只显示第一个字母。

Example: "Apple"示例:“苹果”

A____ --> that's what you actually see. A____ --> 这就是你实际看到的。 Now, the player has to input a letter/char and if it is inculded in the String "Apple", the correct letter will be added.现在,玩家必须输入一个字母/字符,如果它包含在字符串“Apple”中,则会添加正确的字母。

Example: input = e A___e示例:输入 = e A___e

Thx.谢谢。

You can use String.IndexOf .您可以使用String.IndexOf

Example:例子:

var str = "Apple";
var c = 'p';
var i = str.IndexOf(c);
// i will be the index of the first occurrence of 'p' in str, or -1 if not found.

if (i == -1)
{
    // not found
}
else
{
    do
    {
        // do something with index i, which is != -1
        i = str.IndexOf(c, i + 1);
    } while (i != -1);
}

If you want to find all letter indices, you can try this LINQ solution:如果要查找所有字母索引,可以尝试以下 LINQ 解决方案:

var str = "Apple";
var letter = 'p';

var charIndexMap = str
    .Select((ch, idx) => (ch, idx))
    .GroupBy(pair => pair.ch)
    .ToDictionary(entry => entry.Key, 
                  entry => entry.Select(pair => pair.idx));

if (charIndexMap.TryGetValue(letter, out var value))
{
    Console.WriteLine("[" + string.Join(", ", value) + "]");
} else
{
    // not found
}

Output:输出:

[1, 2]

Explanation:解释:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何检查一个字符串包含一个字母空格字母空格和另一个字母 C# - How can i check of a string contains a letter space letter space and anotherl letter C# 如何在 C# 中将字符串的每三个字母大写? - How can I capitalize every third letter of a string in C#? C#如何查找闪存盘字母并在目录/字符串中使用它 - C# how to find the flashdrive letter and use it in a directory/string 如何使用 C# 查找符号后面的字母是大写还是另一个符号 - How can I find if a letter following a symbol is in uppercase OR is another symbol using C# C#:如何仅从字符串中返回第一组大写字母单词? - C#: How can I only return the first set of capital letter words from a string? 如何在C#中的重复字符串之间找到一个字符串? - How can I find a string between repeated strings in C#? C#-如何阻止按键上的字母键入? - C# - How can I block the typing of a letter on a key press? 如何从列表中检索特定字符串,特别是C#中以某个字母开头的字符串? - How can you retreive specific strings from a list, specifically strings that start with a certain letter in C#? 如何检查字符串的第一个字符,如果是字母,C# 中的任何字母 - How to check first character of a string if a letter, any letter in C# C# WinForms:如果按下某个键,我如何将特定字母写入 datagridview 单元格? - C# WinForms: How do I write a specific letter to a datagridview cell if a certain key is pressed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM