C# 如何将字符串拆分和修剪成一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1728303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:18:39  来源:igfitidea点击:

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

c#.netsplittrim

提问by Edward Tanguay

I want to split this line:

我想拆分这一行:

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

into an array of their trimmed versions:

成一系列他们的修剪版本:

"First Name"
"string"
"firstName"

How can I do this all on one line?The following gives me an error "cannot convert type void":

我怎样才能在一条线上完成这一切?以下给我一个错误“无法转换类型void”:

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

采纳答案by Cédric Rup

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 方法采用 Action(采用 T 并返回 void)作为参数,您的 lambda 返回一个字符串作为 string.Trim 返回一个字符串

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

Foreach 扩展方法旨在修改集合中对象的状态。由于字符串是不可变的,这将不起作用

Hope it helps ;o)

希望它有帮助;o)

Cédric

塞德里克

回答by Guffa

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

ForEach方法不返回任何内容,因此您不能将其分配给变量。

Use the Selectextension method instead:

改用Select扩展方法:

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

回答by Matt Breckon

Because p.Trim() returns a new string.

因为 p.Trim() 返回一个新字符串。

You need to use:

您需要使用:

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

回答by Lawrence Phillips

Alternatively try this:

或者试试这个:

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

回答by LawMan

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

回答by user2826608

try using Regex :

尝试使用正则表达式:

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

回答by Hung Vu

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

解释模式 [,;\s]:匹配出现的 , ; 或空格字符

回答by foxjazzHack

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

拆分返回 string[] 类型。写一个扩展方法:

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