0

I want to get the index of a word in a string array. for example, the sentence I will input is 'I love you.' I have words[1] = love, how can I get the position of 'love' is 1? I could do it but just inside the if state. I want to bring it outside. Please help me. This is my code.

 static void Main(string[] args)
    {
        Console.WriteLine("sentence: ");
        string a = Console.ReadLine();
        String[] words = a.Split(' ');
        List<string> verbs = new List<string>();
        verbs.Add("love");
        int i = 0;
        while (i < words.Length) {
            foreach (string verb in verbs) {
                if (words[i] == verb) {
                    int index = i;
                    Console.WriteLine(i);

                }
            } i++;
        }

        Console.ReadKey();
    } 
0

3 Answers 3

1

I could do it but just inside the if state. I want to bring it outside.

Your code identifies the index correctly, all you need to do now is storing it for use outside the loop.

Make a list of ints, and call Add on it for the matches that you identify:

var indexes = new List<int>();
while (i < words.Length) {
    foreach (string verb in verbs) {
        if (words[i] == verb) {
            int index = i;
            indexes.Add(i);
            break;
        }
    }
    i++;
}

You can replace the inner loop with a call of Contains method, and the outer loop with a for:

for (var i = 0 ; i != words.Length ; i++) {
    if (verbs.Contains(words[i])) {
        indexes.Add(i);
    }
}

Finally, the whole sequence can be converted to a single LINQ query:

var indexes = words
    .Select((w,i) => new {w,i})
    .Where(p => verbs.Contains(p.w))
    .Select(p => p.i)
    .ToList();
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example

var a = "I love you.";
var words = a.Split(' ');
var index = Array.IndexOf(words,"love");
Console.WriteLine(index);

Comments

0
private int GetWordIndex(string WordOrigin, string GetWord)
{
    string[] words = WordOrigin.Split(' ');

    int Index = Array.IndexOf(words, GetWord);

    return Index;
}

assuming that you called the function as GetWordIndex("Hello C# World", "C#");, WordOrigin is Hello C# World and GetWord is C#

now according to the function:

  1. string[] words = WordsOrigin.Split(' '); broke the string literal into an array of strings where the words would be split for every spaces in between them. so Hello C# World would then be broken down into Hello, C#, and World.

  2. int Index = Array.IndexOf(words, GetWord); gets the Index of whatever GetWord is, according to the sample i provided, we are looking for the word C# from Hello C# World that is then splitted into an Array of String

  3. return Index; simply returns whatever index it was located from

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.