簡體   English   中英

如何在 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]

解釋:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM