views:

87

answers:

6

i want to check lot's of thing in a string like i want to check 35 times different differnet index of on a string like

string = "i  am steven"

i want to check that string have i or am and steven and some other thing. if i use indexof on this that code look like ugly then how i can apply all index of on string.

A: 

I'm unsure what you actually want, ideally what I would do is break this apart into an array of words and then loop through those instead, maybe even a dictionary/list and check if it doesn't pre-exist/contains.

Lloyd
+2  A: 

you can break it into words by string.Split or Regex.Split (for complex cases) then build word->index* dictionary. then your checks will be much faster.

* - for long sentences word->list of indexes.

Andrey
A: 

You can parse your input "i am steven" into array of strings: ["i", "am", "steven"], and then check if all required string are in this array.

Michał Niklas
A: 

My approach would be splitting the parts of your string and place them in a Hashtable. After that the looking up would be elegant and not much performance.

Casper Broeren
A: 

The answers so far imply that you are looking for words but from your question, I gather you are looking to test for possibly complex conditions. If you are looking to test for simple exact matches, use an array of strings to hold your conditions, then loop through the array using IndexOf. For example...

        string[] myTests = { "I", "am", "Steven", "King" };
        string data = "I am Steven";

        Dictionary<int, int> testResults = new Dictionary<int,int>();
        for (int idx = 0; idx < myTests.Length; ++idx)
        {
            int strIndex = data.IndexOf(myTests[idx], StringComparison.InvariantCultureIgnoreCase);
            testResults[idx] = strIndex;
        }
        // Each test index in the results dictionary that is >= 0 is a match, -1 is a failed match

But if you have complex requirements, you could consider using a Regular Expression. Here is one idea, but without a clear understanding of what you are trying to accomplish, it may not be right for you.

        //Regex example
        string pattern = @"(I|am|Steven)(?<=\b\w+\b)";
        string data2 = "I am Steven";
        MatchCollection mx = Regex.Matches(data2, pattern);
        foreach (Match m in mx)
        {
            Console.WriteLine("{0} {1} {2}", m.Value, m.Index, m.Length);
        }
        string negativePattern = @"^.*(?!King).*$";
        MatchCollection mx2 = Regex.Matches(data2, negativePattern);
        if (mx2.Count != 1)
            Console.WriteLine("Contains a negative match.");
Les
A: 

I don't get exactly what u wanna it.Hope u want to split the string or find the index postion like this

<pre>

string s = "I am Steven"; int indexofSinSteven = s.IndexOf("S"); string s1 = s.Substring(0, indexofSinSteven); Console.Write(s1);

programmer4programming