找到字符串元素的位置

时间:2016-09-30 10:24:32

标签: c# arrays string

需要一些帮助查找字符串中的特定字母。 我需要找到信件" aeiou"在字符串数组和输出中获取第一个找到的字母的位置。 C#中的所有内容。

string array = "Elephants are dangerous";
string letters = "aeiou";

if (array.All(letters.Contains))
{
 Console.WriteLine("Letter: {0}",letters);
}

我犯了错误?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

我比任何一种循环解决方案更喜欢这个。面对不断变化的要求,这是简洁,明显正确和可维护的。