简体   繁体   中英

Partial String in array of strings

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.

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);

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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