0

Hi,

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++;
            }

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

Any good suggestion?

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by ChrisHunter
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.