1

I'm new to C#, and I'm trying to search a string to see if it contains a member of a string array. If the string does contain something from the array, then I want to record the index number of the array member it found, and then display it.

string stringToBeSearched = "I want to find item2 or item6";
string[] array = { "item1", "item2", "item3" };
// Search stringToBeSearched for anything in array, then enter the array 
// member's index value into int position
int position = //array index number of item found
Console.WriteLine("{0} was found.", array[position]);
Console.ReadLine();

3 Answers 3

1

You can compare each array element with the stringToBeSearched using IndexOf.

string stringToBeSearched = "I want to find item2 or item6";
string[] array = {"item1", "item2", "item3"};

int position;

for (int i = 0; i < array.Length; i++) {
    string str = array[i];

    if (stringToBeSearched.IndexOf(str) >= 0) {
        position = i;
        Console.WriteLine("{0} was found.", str);
        Console.ReadLine();
    }
}

// Result: 
// item2 was found.
Sign up to request clarification or add additional context in comments.

Comments

1

An approach using Linq and Generics

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static void Main(String[] args)
    {
       string[] array1 = "I want to find item2 or item6".Split(' ');
       string[] array2 = {"item1", "item2", "item6"};

       IEnumerable<string> results = array1.Intersect(array2,
                                                     StringComparer.OrdinalIgnoreCase);

       foreach (string s in results)
          Console.WriteLine("{0} was found at index {1}.", 
                            s, 
                            Array.IndexOf(array2, s));

    }
}

Comments

0
string stringToBeSearched = "I want to find item2 or item6";
string[] array = { "item1", "item2", "item3" };

string firstOrDefault = array.FirstOrDefault(stringToBeSearched.Contains);
int position = firstOrDefault == null
   ? -1
   : Array.IndexOf(array, firstOrDefault);

if (position >= 0)
   Console.WriteLine("{0} was found.", array[position]);
else
   Console.WriteLine("Did not find any of the strings.");

Console.ReadLine();

Note that this will find the first matching string. If there are more than one you won't know about the others.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.