C# asp.net 将 CSV 字符串转换为字符串[]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/73385/
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
asp.net Convert CSV string to string[]
提问by Col
Is there an easy way to convert a string from csv format into a string[] or list?
有没有一种简单的方法可以将字符串从 csv 格式转换为字符串 [] 或列表?
I can guarantee that there are no commas in the data.
我可以保证数据中没有逗号。
采纳答案by Timothy Carter
string[] splitString = origString.Split(',');
(Following comment not added by original answerer)Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.
(以下评论未由原始回答者添加)请记住,此答案解决了保证数据中没有逗号的特定情况。
回答by DevelopingChris
CsvString.split(',');
回答by John Sheehan
Get a string[] of all the lines:
获取所有行的 string[]:
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
Then loop through and split those lines (this error prone because it doesn't check for commas in quote-delimited fields):
然后循环并拆分这些行(这很容易出错,因为它不检查引号分隔字段中的逗号):
foreach (string line in lines)
{
string[] items = line.Split({','}};
}
回答by John Sheehan
string test = "one,two,three";
string[] okNow = test.Split(',');
回答by Bob King
string s = "1,2,3,4,5";
string myStrings[] = s.Split({','}};
Note that Split() takes an arrayof characters to split on.
请注意, Split() 需要一个字符数组进行拆分。
回答by Paul van Brenk
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
回答by Ryan Steckler
string[] splitStrings = myCsv.Split(",".ToCharArray());
回答by John Sheehan
If you want robust CSV handling, check out FileHelpers
如果您想要强大的 CSV 处理,请查看FileHelpers
回答by Eric Z Beard
There isn't a simple way to do this well, if you want to account for quoted elements with embedded commas, especially if they are mixed with non-quoted fields.
如果您想考虑带有嵌入逗号的引用元素,特别是当它们与非引用字段混合时,没有一种简单的方法可以很好地做到这一点。
You will also probably want to convert the lines to a dictionary, keyed by the column name.
您可能还想将这些行转换为字典,以列名为键。
My code to do this is several hundred lines long.
我执行此操作的代码长达数百行。
I think there are some examples on the web, open source projects, etc.
我觉得网上有一些例子,开源项目等等。
回答by Panos
Try:
尝试:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
Source: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx
来源:http: //weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx