0

I have an array of strings like {"ABC_DEF_GHIJ", "XYZ_UVW_RST", ...} and want to search if my array contains a string partially matching "ABC_DEF". It should return either index (0) or the string itself ("ABC_DEF_GHIJ"). I tried:

int index = Array.IndexOf(saGroups, "ABC_DEF");

But it returns -1.

4 Answers 4

3

You can use extension methods and Lambda expressions to achieve this.

If you need the Index of the first element that contains the substring in the array elements, you can do this...

int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.

If you need the element's value that contains the substring, just use the array with the index you just got, like this...

string fullString = arrayStrings[index];

Note: The above code will find the first occurrence of the match. Similary, you can use Array.FindLastIndex() method if you want the last element in the array that contains the substring.

You will need to convert the array to a List<string> and then use the ForEach extension method along with Lambda expressions to get each element that contains the substring.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

string[] strArray = { "ABC_DEF_GHIJ", "XYZ_UVW_RST" };
string SearchThisString = "ABC_DEF";
int strNumber;
int i = 0;
for (strNumber = 0; strNumber < strArray.Length; strNumber++)
{
    i = strArray[strNumber].IndexOf(SearchThisString);
    if (i >= 0)
      break;
}
Console.WriteLine("String number: {0}",strNumber);

Comments

0

You can also use Contains:

        string [] arr = {"ABC_DEF_GHIJ", "XYZ_UVW_RST"};
        for (int i = 0; i < arr.Length; i++)
            if (arr[i].Contains("ABC_DEF"))
                return i; // or return arr[i]

Comments

0

Simply loop over your string array and check every element with the IndexOf method if it contains the string you want to search for. If IndexOf returns a value other than -1 the string is found in the current element and you can return its index. If we can not find the string to search for in any element of your array return -1.

static int SearchPartial(string[] strings, string searchFor) {
    for(int i=0; i<strings.Length; i++) {
        if(strings[i].IndexOf(searchFor) != -1)
            return i;
    }
    return -1;
}

See https://ideone.com/vwOERDfor a demo

2 Comments

@djs I was hoping for something like Linq statement or an (unknown to me) API rather than just looping through. Thanks.
@NoBullMan Your question was tagged C# 2.0, so I didn't think Linq was an option.

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.