How do I search for a char in a string using the Contains method.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuzz13
    New Member
    • Jun 2010
    • 110

    #1

    How do I search for a char in a string using the Contains method.

    I am trying to run a test that will examine a selected file for illegal characters. It needs to test each read line before it fails or completes. I have this:

    Code:
    string[] lines = File.ReadAllLines(@newobject.csvDirectory);
    
    string[] illegal = { "/", "*", "\\", "|", 
    ":", "\"", "?", "<", ">" };
                
    
                           
    // Return an error for file with illegal characters
    for (int i = 0; i < lines.Length; i++)
    {
                            
    if (lines[i].Contains(illegal[]))
    {
    newobject.illegalError();
    }
    in this line of code
    Code:
    if (lines[i].Contains(illegal[]))
    I need it to search lines[i] for every declared char in the illegal array.

    Thanks for our help with this.
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    You have to iterate over each element of you char-array and do a check.

    Also you could use string's IndexOfAny-method, which takes a char-array and returns the index of any match.

    Comment

    • Fuzz13
      New Member
      • Jun 2010
      • 110

      #3
      If I understand what indexofany does I like that as my option but I've never used it and don't understand how to impliment it in my code from reading msdn's examples. Any chance you could give me an idea of what it would look like?

      Comment

      • brunoss
        New Member
        • Jun 2010
        • 8

        #4
        The first thing you have to do is to turn your array to a char array because you are seaching for a char not for a string. then do the following

        Code:
        if(lines[i].IndexOfAny(illegal) != -1)
        //in this condition lines[i] has illegal chars

        Comment

        Working...