CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2009
    Posts
    112

    switch statment with characters

    Hi, I'm trying to write some lines of code using a switch statment to see if certain characters are in a string. Is it possible to do this?

    I tried this:

    Code:
                switch (directoryPath.Contains)
                {
                    case ":":
                        //some code
                        break;
                    case "\\":
                        //some code
                        break;
                    case "?":
                        //some code
                        break;
                    default:
                        //some code
                        break;
    but obviously that doesn't work. So is there a way to accomplish this via switch statment?

    Thanks.
    - It's a long way to the top if you want to rock n' roll - AC/DC

    Check out my band and support the music:
    www.blueruinmusic.com

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: switch statment with characters

    That doesn't make any sense. directoryPath.Contains returns a boolean, so the only two cases you can have are true and false.

    Switch statements are meant to be fast/constant lookup speed conditionals. If each 'case' needs to be evaluated at runtime you cannot create a jump table when the code is compiled. Just us if/elseif statements; that's what they are there for.
    If you liked my post go ahead and give me an upvote so that my epee.... ahem, reputation will grow.

    Yes; I have a blog too - http://the-angry-gorilla.com/

  3. #3
    Join Date
    May 2007
    Location
    Denmark
    Posts
    623

    Re: switch statment with characters

    You could do it like this:

    Code:
    for(int i = 0; i < directoryPath.Length; i++)
    {
       switch(directoryPath[i])
       {
           case '?': //do stuff
              break;
       }
    }
    It's not a bug, it's a feature!

  4. #4
    Join Date
    Feb 2009
    Posts
    112

    Re: switch statment with characters

    Quote Originally Posted by BigEd781 View Post
    That doesn't make any sense. directoryPath.Contains returns a boolean, so the only two cases you can have are true and false.
    I know it doesn't make any sense... that's why asked is it possible to do something like it using a switch statment. Nested if's can get so messy.

    Thanks for the replies all.
    - It's a long way to the top if you want to rock n' roll - AC/DC

    Check out my band and support the music:
    www.blueruinmusic.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured