[英]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:解释:
Enumerable.Select
to map over the characters and indices and convert them to (character, index)
tuples.Enumerable.Select
映射字符和索引并将它们转换为(character, index)
元组。Enumerable.GroupBy
to group tuples by character.Enumerable.GroupBy
按字符对元组进行分组。Enumerable.ToDictionary
, which maps each character to an IEnumerable<int>
of indices.Enumerable.ToDictionary
将分组结果转换为字典,它将每个字符映射到索引的IEnumerable<int>
。Dictionary<TKey,TValue>.TryGetValue(TKey, TValue)
to get the associated indices for the letter.Dictionary<TKey,TValue>.TryGetValue(TKey, TValue)
获取字母的关联索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.