C# 使用字符串拆分
我有一条短信 类别2,“带逗号的东西” 当我用“,”分开这个时,它应该给我两个字符串C# 使用字符串拆分,c#,.net,C#,.net,我有一条短信 类别2,“带逗号的东西” 当我用“,”分开这个时,它应该给我两个字符串 类别2 有逗号的东西 但实际上它将字符串从每个逗号中分离出来 我怎样才能达到我预期的结果 Thanx只需调用变量.Split(新字符[]{',},2)。在中完成文档。指定数组中所需的最大字符串数: string[] parts = text.Split(new char[] { ',' }, 2); String.Split在最简单、最快的级别上工作,因此它会在传递给它的所有分隔符上拆分文本,并且它没有双
- 类别2
- 有逗号的东西
Thanx只需调用
变量.Split(新字符[]{',},2)
。在中完成文档。指定数组中所需的最大字符串数:
string[] parts = text.Split(new char[] { ',' }, 2);
String.Split
在最简单、最快的级别上工作,因此它会在传递给它的所有分隔符上拆分文本,并且它没有双引号之类的特殊规则概念
如果您需要一个理解双引号的CSV解析器,那么您可以编写自己的解析器,或者有一些优秀的开源解析器可用-例如,这是我在几个项目中使用过并推荐的解析器。这里有许多事情您可能想做,因此我将介绍一些: 在第一个逗号上拆分
String text = text.Split(new char[] { ',' }, 2);
在每个逗号上分开
String text = text.Split(new char[] {','});
在不在“
最后一张照片取自试试这个:
public static class StringExtensions
{
public static IEnumerable<string> SplitToSubstrings(this string str)
{
int startIndex = 0;
bool isInQuotes = false;
for (int index = 0; index < str.Length; index++ )
{
if (str[index] == '\"')
isInQuotes = !isInQuotes;
bool isStartOfNewSubstring = (!isInQuotes && str[index] == ',');
if (isStartOfNewSubstring)
{
yield return str.Substring(startIndex, index - startIndex).Trim();
startIndex = index + 1;
}
}
yield return str.Substring(startIndex).Trim();
}
}
把你的问题分解成一组简单的规则。你想做什么?你是说你想用逗号分割,但如果逗号用双引号括起来就不行了?上一个例子适用于“not inside”内的字符串。您必须将其作为:
Regex.Split(text,(?=(?:[^\“]*\”[^\“]*”[^\“]*”*”*[^\“]*$)”
如果字符串在“,”中,如OP.Hi-thanx的示例所示,解决方案显示它将字符串与第一个分开“,”它对我有效,但假设有一个字符串My,Name是BreakHead。它应该像这样分开,我的名字是BreakHead?一般的解决方案取决于你们的数据和它能包含什么。检查为您的问题提供的其他答案,它们也提供了很好的解决方案。
public static class StringExtensions
{
public static IEnumerable<string> SplitToSubstrings(this string str)
{
int startIndex = 0;
bool isInQuotes = false;
for (int index = 0; index < str.Length; index++ )
{
if (str[index] == '\"')
isInQuotes = !isInQuotes;
bool isStartOfNewSubstring = (!isInQuotes && str[index] == ',');
if (isStartOfNewSubstring)
{
yield return str.Substring(startIndex, index - startIndex).Trim();
startIndex = index + 1;
}
}
yield return str.Substring(startIndex).Trim();
}
}
foreach(var str in text.SplitToSubstrings())
Console.WriteLine(str);