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

♀尐吖头ヾ 提交于 2019-11-29 19:29:20

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

The ForEach method doesn't return anything, so you can't assign that to a variable.

Use the Select extension method instead:

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

Because p.Trim() returns a new string.

You need to use:

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

Alternatively try this:

string[] parts = Regex.Split(line, "\\s*;\\s*");

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();
    }

try using Regex :

List<string> parts = System.Text.RegularExpressions.Regex.Split(line, @"\s*;\s*").ToList();
foxjazzHack

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;
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!