C # split the string with commas (,). If the field contains commas (,) (Note: fields containing commas must be referenced in double quotation marks), splice them.

Source: Internet
Author: User

Zookeeper


///


/// Split the string with commas (,)
/// If a field contains a comma (Note: fields containing a comma must be referenced in double quotation marks), splice the fields.
/// Remove the double quotation marks of the field
///
///
///
Private static string [] SplitStringWithComma (string splitStr)
{
Var newstr = string. Empty;
List SList = new List ();

Bool isSplice = false;
String [] array = splitStr. Split (new char [] {','});
Foreach (var str in array)
{
If (! String. IsNullOrEmpty (str) & str. IndexOf ('"')>-1)
{
Var firstchar = str. Substring (0, 1 );
Var lastchar = string. Empty;
If (str. Length> 0)
{
Lastchar = str. Substring (str. Length-1, 1 );
}
If (firstchar. Equals ("\"")&&! Lastchar. Equals ("\""))
{
IsSplice = true;
}
If (lastchar. Equals ("\""))
{
If (! IsSplice)
Newstr + = str;
Else
Newstr = newstr + "," + str;

IsSplice = false;
}
}
Else
{
If (string. IsNullOrEmpty (newstr ))
Newstr + = str;
}

If (isSplice)
{
// Add a comma that is lost during split.
If (string. IsNullOrEmpty (newstr ))
Newstr + = str;
Else
Newstr = newstr + "," + str;
}
Else
{
SList. Add (newstr. Replace ("\" "," "). Trim (); // remove double quotation marks and spaces
Newstr = string. Empty;
}
}
Return sList. ToArray ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.