C# 修剪数组中的所有字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1355704/
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 15:33:27  来源:igfitidea点击:

trim all strings in an array

c#.netarraystrim

提问by leora

I have a string that comes in like:

我有一个像这样的字符串:

string email = "[email protected], [email protected], [email protected]";

I want to split it into an array of strings

我想把它拆分成一个字符串数组

If I do this:

如果我这样做:

string[] emails = email.Split(',');

I get spaces in front of each email address (after the first one):

我在每个电子邮件地址前面都有空格(在第一个之后):

emails[0] = "[email protected]"
emails[1] = " [email protected]"
emails[2] = " [email protected]"

What is the best way to get this (either a better way to parse or a way to trim all strings in an array)?

获得它的最佳方法是什么(更好的解析方法或修剪数组中所有字符串的方法)?

emails[0] = "[email protected]"
emails[1] = "[email protected]"
emails[2] = "[email protected]"

采纳答案by nick2083

You could also replace all occurrences of spaces, and so avoid the foreach loop:

您还可以替换所有出现的空格,从而避免 foreach 循环:

string email = "[email protected], [email protected], [email protected]";    
string[] emails = email.Replace(" ", "").Split(',');

回答by skalb

You can use Trim():

您可以使用 Trim():

string email = "[email protected], [email protected], [email protected]";
string[] emails = email.Split(',');
emails = (from e in emails
          select e.Trim()).ToArray();

回答by jscharf

Use String.Trimin a foreachloop, or if you are using .NET 3.5+ a LINQ statement.

使用String.Trim一个foreach循环,或者如果您使用的是.NET 3.5+一个LINQ声明。

回答by Jan Zich

Alternatively, you can split using a regular expression of the form:

或者,您可以使用以下形式的正则表达式进行拆分:

\s*,\s*

i.e.

IE

string[] emails = Regex.Split(email, @"\s*,\s*");

It will consume the surrounding spaces directly.

它会直接消耗周围的空间。

Regular expressions are usually a performance hit, but the example you gave indicates that this is something you plan to do once in your code for a short array.

正则表达式通常会影响性能,但您提供的示例表明这是您计划在代码中为短数组执行的操作。

回答by Brian Rasmussen

Use Regex.Splitto avoid trimming

使用Regex.Split以避免修剪

var emails = Regex.Split(email, @",\s*");

回答by Sam Harwell

Either one of the following would work. I'd recommend the first since it more accurately expresses the joining string.

以下任一方法都可以。我推荐第一个,因为它更准确地表达了连接字符串。

string[] emails = email.Split(new string[] { ", " }, StringSplitOptions.None);
string[] emails = email.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);

回答by Bryan Watts

emails.Split(',').Select(email => email.Trim()).ToArray()

回答by mr.martan

You can use a one line solution like this:

您可以使用这样的单行解决方案:

string[] emails = text.Split(',', StringSplitOptions.RemoveEmptyEntries);
Array.ForEach<string>(emails, x => emails[Array.IndexOf<string>(emails, x)] = x.Trim());

回答by RonSanderson

The answer from Bryan Watts is elegant and simple. He implicitly refers to the array of strings created by the Split().

Bryan Watts 的回答优雅而简单。他隐含地引用了由 Split() 创建的字符串数组。

Also note its extensibility if you are reading a file, and want to massage the data while building an array.

如果您正在读取文件,并希望在构建数组时处理数据,还要注意它的可扩展性。

string sFileA = @"C:\Documents and Settings\FileA.txt";
string sFileB = @"C:\Documents and Settings\FileB.txt";

// Trim extraneous spaces from the first file's data
string[] fileAData = (from line in File.ReadAllLines( sFileA )
                      select line.Trim()).ToArray();

// Strip a second unneeded column from the second file's data
string[] fileBData = (from line in File.ReadAllLines( sFileB )
                      select line.Substring( 0, 21 ).Trim()).ToArray();

Of course, you can use the Linq => notation if you prefer.

当然,如果您愿意,可以使用 Linq => 表示法。

string[] fileBData = File.ReadAllLines( sFileB ).Select( line =>
                             line.Substring( 0, 21 ).Trim()).ToArray();

Although my answer should have been posted as a comment, I don't have enough reputation points to comment yet. But I found this discussion invaluable in figuring out how to massage data while using ReadAllLines().

虽然我的回答应该作为评论发布,但我还没有足够的声誉点来评论。但是我发现这个讨论对于弄清楚如何在使用 ReadAllLines() 时处理数据非常有价值。

回答by Teodor Tite

If you just need to manipulate the entries, without returning the array:

如果您只需要操作条目而不返回数组:

string[] emails = text.Split(',');
Array.ForEach(emails, e => e.Trim());