简体   繁体   English

在字符串C#中查找数组元素

[英]Finding array element within a string C#

I've been looking for a way to check a string for elements of an array and if it contains one of those elements to return the indexOf it but i'm having trouble finding a way to do this. 我一直在寻找一种方法来检查一个字符串的数组元素,如果它包含其中一个元素,以返回indexOf它,但我很难找到一种方法来做到这一点。 Most of my searches end up showing me way to find the indexOf an element in an array or something similar. 我的大部分搜索最终都向我展示了如何找到indexOf数组中的元素或类似的东西。

As a bit of background I'm trying to create a program that takes a string from user input, splits the words of the paragraph into an array, performs certain checks on them and changes them accordingly. 作为一些背景,我正在尝试创建一个从用户输入中获取字符串的程序,将段落的单词拆分为数组,对它们执行某些检查并相应地更改它们。

For instance if the current word starts with a consonant it finds the first vowel and moves all the letters in front of it to the end of the word. 例如,如果当前单词以辅音开头,则它找到第一个元音并将其前面的所有字母移动到单词的末尾。 This is what I tried but it prints an index of 14 so clearly something is wrong: 这是我尝试过但它打印的索引为14,所以显然有些错误:

char[] vowelsList = new char[] { 'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u' };

foreach (char vowel in vowelsList)
{
    if (currentWord.Contains(vowel))
    {
        int index = currentWord.IndexOf(vowel);
        System.Diagnostics.Debug.Write(index);
    }
}

currentWord is the word from the string from the user input that is currently being checked. currentWord是来自当前正在检查的用户输入的字符串中的单词。

Any suggestion on different methods or keywords to try is appreciated. 任何关于尝试不同方法或关键字的建议都表示赞赏。

EDIT 编辑

I apologise the code is actually fine, it was returning 1 and 4 because it was always receiving the input Hello and i was misinterpreting what was going on, I'm a bit of an idiot sometimes. 我道歉代码实际上很好,它返回1和4,因为它总是收到输入Hello,我误解了发生的事情,我有时候有点像个白痴。 I guess then my question would be how to get this code to only find the index of the first vowel but a poster has already stated how to do that, thank you all for the help and suggestions, most of which I have implemented. 我想那时我的问题是如何让这段代码只找到第一个元音的索引,但是海报已经说明了如何做到这一点,谢谢大家的帮助和建议,其中大部分是我实施的。

You probably want to use String.IndexOfAny , which returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters. 您可能希望使用String.IndexOfAny ,它返回指定的Unicode字符数组中此实例中第一个出现的从零开始的索引。

If no character is found, it returns -1 . 如果未找到任何字符,则返回-1

var index = currentWord.IndexOfAny(vowelsList);
if (index >= 0)
{ 
    // do stuff
}

Note that, as stated on MSDN, this method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar value are the same. 请注意,如MSDN所述,此方法执行序数 (区域性不敏感)搜索,其中只有在Unicode标量值相同时才将字符视为与另一个字符等效。 To perform a culture-sensitive search, you would need to use an overload of CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character. 要执行区分大小写的搜索,您需要使用CompareInfo.IndexOf方法的重载,其中Unicode标量值表示预组合字符。

IndexOf returns -1 if the string doesn't contain the vowel so just use that 如果字符串不包含元音,则IndexOf返回-1,因此只需使用它

The zero-based index position of value if that character is found, or -1 if it is not. 如果找到该字符,则从零开始的索引值位置,如果不是,则返回-1。

int index = currentWord.IndexOf(vowel);    
if (index != -1)
{
    System.Diagnostics.Debug.Write(index);
}

And the obligatory linq answer: 强制性的linq回答:

vowelsList.Select(v => currentWord.IndexOf(v))
          .Where(idx => idx != -1)
          .ToList();

You can also half the number of iterations you have to make by using ToLower 您还可以使用ToLower进行一半的迭代次数

char[] vowelsList = new char[] { 'a', 'e', 'i', 'o', 'u' };

int index = currentWord.ToLower().IndexOf(vowel);    
if (index != -1)
{
    System.Diagnostics.Debug.Write(index);
}

vowelsList.Select(v => currentWord.ToLower().IndexOf(v))
          .Where(idx => idx != -1)
          .ToList();

If you just want the first index you can just turn your current code into an extension method as so 如果您只想要第一个索引,可以将当前代码转换为扩展方法

private int FirstIndexOfVowel(this string s)
{
    char[] vowelsList = new char[] { 'a', 'e', 'i', 'o', 'u' };
    foreach(char v in vowelsList)
    {
        int idx = s.ToLower().IndexOf(v);
        if(idx != -1)
            return idx;
    }
    return -1;
}


int idx = currentWord.FirstIndexOfVowel();

Linq version for first index only (returns null if none found) Linq版本仅用于第一个索引(如果没有找到则返回null)

vowelsList.Select(v => currentWord.ToLower().IndexOf(v))
          .FirstOrDefault(idx => idx != -1);

Is it what you are looking for ? 这是你在找什么?

   char[] vowelsList = new char[] {'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u'};

        foreach (char vowel in vowelsList)
        {
            if (currentWord.Contains(vowel))
            {
                int index = currentWord.IndexOf(vowel);

                Console.WriteLine(currentWord.Substring(index, currentWord.Length - index) +
                                  currentWord.Substring(0, index));
            }
        }

This is what I tried but it prints an index of 14 so clearly something is wrong 这是我尝试过但它打印的索引为14,所以显然有些不对劲

You don't understand why it returns 14 even if the array doesn't contain so many characters? 你不明白为什么它返回14,即使数组不包含这么多字符? That means you expect that it returns the index of the char in the char[] but... 这意味着你期望它返回char[] char的索引但是......

int index = currentWord.IndexOf(vowel);

returns the index of the char in the word. 返回单词中char的索引。

This should work as expected, i use Array.IndexOf to find the index of the char in the array: 这应该按预期工作,我使用Array.IndexOf来查找数组中char的索引:

foreach (char vowel in vowelsList)
{
    if (currentWord.Contains(vowel))
    {
        int index = Array.IndexOf(vowelsList, vowel);
        //...
    }
}

Another approach is not to use foreach but a for-loop which already knows the index. 另一种方法不是使用foreach而是使用已经知道索引的for循环。

An example that will give you a nice and manageable overview of all vowels (or whatever your criteria for being in the array is): 这个例子可以让您对所有元音(或者您在数组中的任何条件)进行良好且易于管理的概述:

var word = "Stupendous!";
char[] vowelsList = 
          new char[] { 'A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u' };

// Get all matches in a word, along with their positions:
var allVowels = word.Select((chr, pos) => new {chr, pos})
                    .Where(match => vowelsList.Contains(match.chr));

var positionOfFirst = allVowels.First().pos; 

Update: Tim Schmelter is probably right, so I`ll updated my answer to include the position of the characters in the array: 更新: Tim Schmelter可能是对的,所以我会更新我的答案,包括数组中字符的位置:

var allVowels = word
                 .Where(match => vowelsList.Contains(match))
                 .Select((chr, pos) => 
                           new {chr, pos, PosInArray = 
                                             Array.IndexOf(vowelsList, chr)});

var positionOfFirst = allVowels.First().PosInArray;

That last piece of code will return (for allVowels ) an IEnumerable containing the following data: 最后一段代码将返回(对于allVowels )包含以下数据的IEnumerable:

{ {chr = u, pos = 2, PosInArray = 9}, 
  {chr = e, pos = 4, PosInArray = 3}, 
  {chr = o, pos = 7, PosInArray = 7}, 
  {chr = u, pos = 8, PosInArray = 9} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM