简体   繁体   English

分割字符串和CSV C#

[英]Splitting strings and CSV C#

I have written an exporter that exports strings to .csv 我写了一个将字符串导出到.csv的导出器

Thing is, some of these strings have commas in already: 问题是,其中一些字符串中已经有逗号了:

2 CAR MODELS, 5 TEAMS,2 CAR MODELS, 5 TEAMS

You see that the commas added in the strings by hand have one white space after them. 您会看到手工添加在字符串中的逗号后面有一个空格。 The one I added has no whitespace. 我添加的那个没有空格。

I have written code to read the string and split it: 我已经编写了读取字符串并将其分割的代码:

while ((line = stringReader.ReadLine()) != null)
        {
            // split the string at each comma
            string[] split = line.Split(new char[] { ',' });

What i need is for the string to split at ',' and NOT at ', '. 我需要的是将字符串拆分为','而不是','。

Any ideas? 有任何想法吗?

I cant use any third party code like this: 我不能使用任何这样的第三方代码:

http://www.codeproject.com/KB/database/CsvReader.aspx http://www.codeproject.com/KB/database/CsvReader.aspx

您可以使用TextFieldParser它位于Microsoft.VisualBasic.FileIO命名空间中,因此不能位于“ thirdparty”中。

You might consider using Regex.Split(String arg1, String arg2) . 您可以考虑使用Regex.Split(String arg1,String arg2) It should allow you to split a string according to a regular expression. 它应该允许您根据正则表达式拆分字符串。

You can then use a regex like this: 然后,您可以使用如下所示的正则表达式:

,[^\s]+

This should allow you to split values which have a comma but are not followed with one or more spaces. 这应该允许您拆分具有逗号但后面没有一个或多个空格的值。

You can do this with Regex.Split in the System.Text.RegularExpressions namespace. 您可以使用System.Text.RegularExpressions命名空间中的Regex.Split来执行此操作。

http://msdn.microsoft.com/en-us/library/b5k3ak3e.aspx http://msdn.microsoft.com/zh-CN/library/b5k3ak3e.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM