Wednesday, March 23, 2011

string split based on char \

Got a bit of a mind freeze at the moment. I have the following syntax:-

        string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split('\');

and I get an error on the split character. Can anyone advise on how I can do the split using the \ character as the delimiter?

Cheers

From stackoverflow
  • Use

    Split('\\')
    

    "\" is an escape character.

    anonym0use : cheers for that!
  • \ is an excape character in C#.

    You need to do one of the following:

    Split('\\');
    

    or

    Split(@'\');
    
  • Am I wrong, or would you need an additional \ before that one to escape it?

  • Split takes a char[] as a parameter, not a char. Try;

    string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split(new char[] {'\\'});
    
    Stu Mackellar : Why the downvote? The non-escaped character is only part of the story, there is no overload of String.Split that takes a single char.
  •  string[] repname = Thread.CurrentPrincipal.Identity.ToString().Split(new string[]{"\\"}, StringSplitOptions.None);
    

0 comments:

Post a Comment