I have a problem on search text from a string. I'm able to find it but my method is slow.
Let say I got a string that contain items and I need to find out which items come first. So I find all the item by .IndexOf("..."). Then find the min value to know which come first. So the problem is when the string is lengthy like few MB. Then my searching method will be very very slow.

Here is my example:

int[] index = new int[6];   //global in class

private void Searching()
    string Src = "apple orange kiwi lemon honey coconut ... ... ";

    int _iMinIndex;

    index[0] = Src.IndexOf("apple");
    index[1] = Src.IndexOf("orange");
    index[2] = Src.IndexOf("kiwi");
    index[3] = Src.IndexOf("lemon");
    index[4] = Src.IndexOf("honey");
    index[5] = Src.IndexOf("coconut");

    if(!Get_PositiveMinValue(ref int _iMinIndex))
        textBox1.Text = "not found";

        private bool Get_PositiveMinValue(ref int _iMinIndex)
            int iNegativeCnt = 0;
            int _iMinIndexValue;

            _iMinIndex = 0;
            _iMinIndexValue = iIndex[0];
            if (iIndex[0] < 0) iNegativeCnt++;
            for (int i = 1; i < iIndex.Length; i++)
                if (iIndex[i] >= 0 && iIndex[i] < _iMinIndexValue)
                    //update the 1st min positive value
                    _iMinIndex = i;
                    _iMinIndexValue = iIndex[i];
                else if (iIndex[i] < 0)
                    if (iIndex[i] < 0) iNegativeCnt++;

                if (iNegativeCnt == iIndex.Length)
                    return false;
                    return true;
            catch (Exception) { return false; }

Any good suggestion?

If you're strings will always contain words seperated by spaces you cour tokenise the string by the spaces.

You can also convert the string to a char array, loop through the array until you come to the first letter of a required word and keep looping through the array until the sequential array indexes match a given word.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.