![](/img/trans.png)
[英]How can i check of a string contains a letter space letter space and anotherl letter C#
[英]How can I find a certain letter in a String in C#?
如何在字符串中搜索某個字母(字符)?
我必須編寫一個小謎語。 您基本上必須猜出一個未知單詞的正確字母。 只顯示第一個字母。
示例:“蘋果”
A____ --> 這就是你實際看到的。 現在,玩家必須輸入一個字母/字符,如果它包含在字符串“Apple”中,則會添加正確的字母。
示例:輸入 = e A___e
謝謝。
您可以使用String.IndexOf
。
例子:
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);
}
如果要查找所有字母索引,可以嘗試以下 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
}
輸出:
[1, 2]
解釋:
Enumerable.Select
映射字符和索引並將它們轉換為(character, index)
元組。Enumerable.GroupBy
按字符對元組進行分組。Enumerable.ToDictionary
將分組結果轉換為字典,它將每個字符映射到索引的IEnumerable<int>
。Dictionary<TKey,TValue>.TryGetValue(TKey, TValue)
獲取字母的關聯索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.