C#
split
方法','
一个字符串,其分隔符为""
,当逗号位于文本块""AAC","AAC Holdings, Inc.""
内时,小心不要分割。
例如,如果字符串包含
[]
拆分应该返回(string[]
会假装它是split
返回的[AAC] [AAC Holdings, Inc.]
的数组元素
[AAC] [AAC Holdings] [Inc.]
不是
void foo(int & ri)
{
std::cout << "do something\n";
}
int main()
{
int i = 5;
foo(i);
return 0;
}
答案 0 :(得分:4)
这可能最好使用Microsoft.VisualBasic
库(在reference
),Microsoft.VisualBasic.FileIO
namespace
,TextFieldParser
类中添加,如下所示:
using Microsoft.VisualBasic.FileIO;
...
string str = "\"AAC\",\"AAC Holdings, Inc.\"";
List<string[]> param = new List<string[]>();
string[] words; //add intermediary reference
using (TextFieldParser parser = new TextFieldParser(new StringReader(str))) {
parser.Delimiters = new string[] { "," }; //the parameter must be comma
parser.HasFieldsEnclosedInQuotes = true; //VERY IMPORTANT
while ((words = parser.ReadFields()) != null)
param.Add(words);
}
foreach (var par in param)
Console.WriteLine(string.Join("; ", par));
结果:
AAC; AAC Holdings, Inc.
请注意TextFieldParser
HasFieldsEnclosedInQuotes = true
Bundle bundle = new Bundle();
bundle.putString("showCase" , "Case1");
Fragment1 fragment = new Fragment1();
fragment.setArguments(bundle);
是专为您的案例设计的。
答案 1 :(得分:3)
您可以使用","
分隔符
var description = "\"AAC\",\"AAC Holdings, Inc.\"";
var listText = description.Split(new[] { "\",\"" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in listText)
{
Console.WriteLine(s.Replace("\"",""));
}
Console.ReadLine();
返回
AAC
AAC Holdings, Inc.
答案 2 :(得分:0)
以下是您可以使用的免费图书馆:FileHelpers。我建议您使用图书馆,因为它会为您处理所有这些恶作剧。请查看this,因为他们会将数据加载到DataTable
以完成您需要的操作,我也会在此处复制代码,以防链接失效:
string path = @"C:\";
using (OleDbConnection conn =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
path + @";Extended Properties=""Text;HDR=No;FMT=Delimited"""))
{
using (OleDbCommand cmd =
new OleDbCommand("SELECT * FROM verylarge.csv", conn))
{
conn.Open();
using (OleDbDataReader dr =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (dr.Read())
{
int test1 = dr.GetInt32(0);
int test2 = dr.GetInt32(1);
int test3 = dr.GetInt32(2);
int test4 = dr.GetInt32(3);
int test5 = dr.GetInt32(4);
}
}
}
}