1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

C#: How to split a string?

Discussion in 'C, C++, C#' started by kytro360, Sep 12, 2011.

  1. kytro360

    kytro360 Power Member

    Joined:
    Jan 12, 2010
    Messages:
    703
    Likes Received:
    732
    Im importing text that says the username and password of the user in this format username:password and want to split the string so i can only use the username or only the password in certain peices of code.
     
  2. artizhay

    artizhay BANNED BANNED

    Joined:
    Nov 21, 2010
    Messages:
    1,867
    Likes Received:
    1,335
    Code:
    string loginString = "username:password";
    string[] loginArr = loginString.Split(':');
     
    • Thanks Thanks x 1
  3. kytro360

    kytro360 Power Member

    Joined:
    Jan 12, 2010
    Messages:
    703
    Likes Received:
    732
    Awesome thanks :)
     
  4. something77

    something77 Registered Member

    Joined:
    Jan 6, 2010
    Messages:
    73
    Likes Received:
    10
    If you just wanted one part you can use .substring(...), but for your example above, split is best
     
  5. xenon2010

    xenon2010 Regular Member

    Joined:
    Apr 27, 2010
    Messages:
    231
    Likes Received:
    48
    Occupation:
    web and desktop apps programmer
    Location:
    prison
    Home Page:
    this is not efficient way to do this...
    what if the username has ":" or the password has ":" the script will crash..
    you need to make it like "username($\|/$)password" or something harder to be duplicated inside the value of the username or password.. perhaps a character that will never be used in the username or pass...
     
  6. ShiftySituation

    ShiftySituation Power Member

    Joined:
    Apr 15, 2010
    Messages:
    621
    Likes Received:
    314
    Occupation:
    Having fun
    Location:
    Jacksonville, FL
    .Split only works for a single character, so your idea wouldn't work. Code doesn't crash if it is written inside try/catch blocks...
     
  7. xenon2010

    xenon2010 Regular Member

    Joined:
    Apr 27, 2010
    Messages:
    231
    Likes Received:
    48
    Occupation:
    web and desktop apps programmer
    Location:
    prison
    Home Page:
    you are wrong...
    split function can work with multiple characters and the best way to do this is to use regex to validate the input and extract the data.. but still this could be achieved with split function..
    here:
    Code:
    string text = "username($\|/$)password";
    string[] data = text.Split(new string[] { "($\|/$)" }, StringSplitOptions.None);
    personally, I prefer to use regex as I can validate the input and extract it easily.