How can I split and trim a string into parts all on one line?

前端 未结 8 1096
一个人的身影
一个人的身影 2020-12-22 21:08

I want to split this line:

string line = \"First Name ; string ; firstName\";

into an array of their trimmed versions:

\"Fi         


        
相关标签:
8条回答
  • 2020-12-22 21:14

    Try

    List<string> parts = line.Split(';').Select(p => p.Trim()).ToList();
    

    FYI, the Foreach method takes an Action (takes T and returns void) for parameter, and your lambda return a string as string.Trim return a string

    Foreach extension method is meant to modify the state of objects within the collection. As string are immutable, this would have no effect

    Hope it helps ;o)

    Cédric

    0 讨论(0)
  • 2020-12-22 21:15

    try using Regex :

    List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();
    
    0 讨论(0)
  • 2020-12-22 21:19

    Here's an extension method...

        public static string[] SplitAndTrim(this string text, char separator)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return null;
            }
    
            return text.Split(separator).Select(t => t.Trim()).ToArray();
        }
    
    0 讨论(0)
  • 2020-12-22 21:20

    Split returns string[] type. Write an extension method:

    public static string[] SplitTrim(this string data, char arg)
    {
        string[] ar = data.Split(arg);
        for (int i = 0; i < ar.Length; i++)
        {
            ar[i] = ar[i].Trim();
        }
        return ar;
    }
    

    I liked your solution so I decided to add to it and make it more usable.

    public static string[] SplitAndTrim(this string data, char[] arg)
    {
        return SplitAndTrim(data, arg, StringSplitOptions.None);
    }
    
    public static string[] SplitAndTrim(this string data, char[] arg, 
    StringSplitOptions sso)
    {
        string[] ar = data.Split(arg, sso);
        for (int i = 0; i < ar.Length; i++)
            ar[i] = ar[i].Trim();
        return ar;
    }
    
    0 讨论(0)
  • 2020-12-22 21:20

    Use Regex

    string a="bob, jon,man; francis;luke; lee bob";
    			String pattern = @"[,;\s]";
                String[] elements = Regex.Split(a, pattern).Where(item=>!String.IsNullOrEmpty(item)).Select(item=>item.Trim()).ToArray();;			
                foreach (string item in elements){
                    Console.WriteLine(item.Trim());

    Result:

    bob

    jon

    man

    francis

    luke

    lee

    bob

    Explain pattern [,;\s]: Match one occurrence of either the , ; or space character

    0 讨论(0)
  • 2020-12-22 21:24

    Alternatively try this:

    string[] parts = Regex.Split(line, "\\s*;\\s*");
    
    0 讨论(0)
提交回复
热议问题