查找字符串元素的位置

本文关键字:位置 元素 字符串 查找 | 更新日期: 2023-09-27 18:09:51

需要帮助查找字符串中的特定字母。我需要在字符串数组和输出中找到字母"aeiou",以获得第一个找到的字母的位置。c#中的一切

string array = "Elephants are dangerous";
string letters = "aeiou";
if (array.All(letters.Contains))
{
 Console.WriteLine("Letter: {0}",letters);
}

哪里出错了?

查找字符串元素的位置

int? minIndex =
 letters
 .Select(l => (int?)array.IndexOf(l))
 .Where(idx => idx != -1)
 .Min();

比起任何一种循环解决方案,我更喜欢这个。这是简洁的,显然是正确的,并且在面对不断变化的需求时是可维护的。

string array = "Elephants are dangerous";
char[] letters = ("aeiou").ToCharArray(); // make char array to iterate through all characters. you could make this also "inline" in the foreach i just left it her so you see what's going on.
int firstIndex = int.MaxValue;
char firstletter = '?';
foreach (char letter in letters) // iterate through all charecters you're searching for
{
    int index = array
        .ToLower() // to lower -> remove this line if you want to have case sensitive search
        .IndexOf(letter); // get the index of the current letter
    //check if the character is found and if it's the earliest position
    if (index != -1 && index < firstIndex ) 
    {
        firstIndex = index;
        firstletter = letter;
    }
}
Console.WriteLine("Letter: {0} @ {1}", firstletter, firstIndex);

编辑如果你喜欢使用LINQ:

注意:请查看"usr"的答案。它更干净;-)

string array = "Elephants are dangerous";
char[] letters = ("aeiou").ToCharArray();
char firstletter = array.ToLower().First(c => letters.Contains(c));
int firstIndex = array.ToLower().IndexOf(firstletter);
Console.WriteLine("Letter: {0} @ {1}", firstletter, firstIndex);

EDIT2现在你有一个正则表达式

string array = "Elephants are dangerous";
Match match = Regex.Match(array.ToLower(), "[aeiou]");
if (match.Success)
{
    Console.WriteLine("Letter: {0} @ {1}", match.Value, match.Index);
}
https://www.dotnetperls.com/regex