search my String[]

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?cm9kY2hhcg==?=

    search my String[]

    hey all,
    can someone please show me how to search my String[] array to see if an
    element "contains" a certain string constant and then return the index value
    of the found element?

    thanks,
    rodchar
  • Peter Morris

    #2
    Re: search my String[]

    public int IndexOfSubStrin g(string[] values, string value)
    {
    for (int index = 0; index < values.Length; index++)
    if (values[index].IndexOf(value) -1)
    return index;
    return -1;
    }


    Comment

    • =?Utf-8?B?cm9kY2hhcg==?=

      #3
      RE: search my String[]

      Thanks for the help,
      rod.

      "rodchar" wrote:
      hey all,
      can someone please show me how to search my String[] array to see if an
      element "contains" a certain string constant and then return the index value
      of the found element?
      >
      thanks,
      rodchar

      Comment

      • Gilles Kohl [MVP]

        #4
        Re: search my String[]

        On Mon, 24 Mar 2008 08:48:01 -0700, rodchar
        <rodchar@discus sions.microsoft .comwrote:
        >hey all,
        >can someone please show me how to search my String[] array to see if an
        >element "contains" a certain string constant and then return the index value
        >of the found element?
        Here's something straightforward :

        static int FindStringConta iningText(strin g[] strings, string textToFind)
        {
        for(int i = 0; i < strings.Length; i++)
        {
        if(strings[i].Contains(textT oFind))
        {
        return i;
        }
        }
        return -1;
        }

        Returns the index of the string containing the text you're looking for, or -1
        if not found.

        call e.g. like so:

        int foundPosition = FindStringConta iningText(theAr ray, "42");

        With C# 3.0, you could also use LINQ:

        foundPosition = Enumerable.Rang e(0, theArray.Length ).First(i =>
        theArray[i].Contains("42") );

        Regards,
        Gilles.

        Comment

        • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

          #5
          Re: search my String[]

          Jon Skeet [C# MVP] wrote:
          Jon Skeet [C# MVP] <skeet@pobox.co mwrote:
          >rodchar <rodchar@discus sions.microsoft .comwrote:
          >>can someone please show me how to search my String[] array to see if an
          >>element "contains" a certain string constant and then return the index value
          >>of the found element?
          >See Array.IndexOf.
          >
          Whoops - apologies for this, I didn't read the question quite carefully
          enough :(
          It is actually pretty close.

          With latest and greatest:

          Array.FindIndex (strarr, (string strelm) =strelm.Contain s(fndstr))

          Arne

          Comment

          Working...