locked
How can i get the trimmed string when i split ? RRS feed

  • Question

  • User1253338400 posted

    Hi ,

    I have the following 

    mystring = firstname; lastname 

    How can I get the trimmed string when I split using the following

    List<string> cols = mystring.Split(';').ToList();

    at the moment I get a list with firstname  but lastname has a leading space. How can I trim before putting in the list ?

    thanks

    Tuesday, November 12, 2019 3:07 AM

Answers

  • User-821857111 posted

    List<string> cols = mystring.Split(';').Select(s => s.Trim()).ToList();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 12, 2019 8:55 AM

All replies

  • User-821857111 posted

    List<string> cols = mystring.Split(';').Select(s => s.Trim()).ToList();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 12, 2019 8:55 AM
  • User-1780421697 posted
    string line = " test; test1  ;     test2;";
    string[] result = Array.ConvertAll(line.Split(';'), p => p.Trim());
    
    var result = line.Split(';').Select(p => p.Trim()).Where(p => !string.IsNullOrWhiteSpace(p)).ToArray();

    Tuesday, November 12, 2019 9:23 AM
  • User288213138 posted

    Hi robby32,

    at the moment I get a list with firstname  but lastname has a leading space. How can I trim before putting in the list ?

    You can use a string to split it.

    List<string> cols = Regex.Split(mystring, "; ", RegexOptions.IgnoreCase).ToList();

    The result:

    Best regards,

    Sam

    Tuesday, November 12, 2019 9:43 AM