How to split string by string with multiple inverted commas in string in c#
How to split a string by "," where " is part of string to split by.
string[] stringSeparator = new string[] {","};
while (!sr.EndOfStream) {
string strline = sr.ReadLine();
string[] _values = strline.Split(stringSeparator, StringSplitOptions.None);
for (int entry = 0; entry < _values.Length; entry++) {
MessageBox.Show(_values[entry]);
}
}
Tried to use "","" but it seems to return开发者_运维问答 whole line instead of just part of it.
Edit:
String to split (example):
First line:
"24446022020000000174234443,""PLN"",""NVESTMENT SOMETHING "",""2011-03-06"",""2011-03-07"",""-25,21"""
2nd line:
"1,""E"",""2011-03-04"",""2011-03-07"",""2011-03-07"",""1,00"",""0000000100000001"",""UZNANIE sdsd ELIXIR"",""45555550040000001244580001"",""Some Client (E)KLIENT NR:0000000100000001"",""example something"",""73116022447246000100000001"""
If you want to represent literal quotation marks in a string, you need to escape it (or double it in a verbatim string literal).
i.e.,
new string[] { "\",\"" };
//or
new string[] { @""",""" };
As for why you're getting the values you were getting, consider the ways you were typing it:
string[] stringSeparator = new string[] { "," };
Is a string array containing a single string, just a comma ,
. It will split but you probably didn't get the values you were expecting.
string[] stringSeparator = new string[] { "","" };
Is a string array containing a two strings, both empty (blank) strings. Perhaps it would be clearer if it was typed as: new string[] { "", "" };
. The Split()
function ignores empty string delimiters so it doesn't split anything.
string[] stringSeparator = new string[] { "\",\"" };
Is a string array containing a single string, double-quote comma double-quote ","
. It should get you everything between the ","
in your strings.
Try
char[] delimiters = new char[] { ',', '"' };
string[] parts = value.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
Trim first and then split to get rid of all quotes.
string[] stringSeparator = new string[] {"\",\""};
while (!sr.EndOfStream)
{
//trim removes first and last quote since they are not removed by the split
string line = sr.ReadLine().Trim('"');
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++)
MessageBox.Show(values[index]);
}
string strline = sr.ReadLine();
string[] abc = strline.Split('"');
abc = Array.FindAll(abc, val => val != ",").ToArray();
string result[] = Array.FindAll(abc, val => val != "").ToArray();
精彩评论