您的位置:首页 > 编程语言 > C#

C#以逗号拆分字符串,若字段中包含逗号(备注:包含逗号的字段必须有双引号引用)则对其进行拼接处理

2014-01-03 13:50 387 查看


/// <summary>

/// 以逗号拆分字符串

/// 若字段中包含逗号(备注:包含逗号的字段必须有双引号引用)则对其进行拼接处理

/// 最后在去除其字段的双引号

/// </summary>

/// <param name="splitStr"></param>

/// <returns></returns>

private static string[] SplitStringWithComma(string splitStr)

{

var newstr = string.Empty;

List<string> sList = new List<string>();

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)

{

//添加因拆分时丢失的逗号

if (string.IsNullOrEmpty(newstr))

newstr += str;

else

newstr = newstr + "," + str;

}

else

{

sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的双引号和首尾空格

newstr = string.Empty;

}

}

return sList.ToArray();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐