如果我有一个字符串:str1|str2|str3|srt4
并用|
作为分隔符解析它。我的输出将是 str1 str2 str3 str4
。
但是如果我有一个字符串:str1||str3|str4
输出将是str1 str3 str4
。我正在寻找的输出是 str1 null/blank str3 str4
。
我希望这是有道理的。
string createText = "srt1||str3|str4";
string[] txt = createText.Split(new[] { '|', ',' },
StringSplitOptions.RemoveEmptyEntries);
if (File.Exists(path))
{
//Console.WriteLine("{0} already exists.", path);
File.Delete(path);
// write to file.
using (StreamWriter sw = new StreamWriter(path, true, Encoding.Unicode))
{
sw.WriteLine("str1:{0}",txt[0]);
sw.WriteLine("str2:{0}",txt[1]);
sw.WriteLine("str3:{0}",txt[2]);
sw.WriteLine("str4:{0}",txt[3]);
}
}
输出
str1:str1
str2:str3
str3:str4
str4:"blank"
那不是我要找的。这就是我想要编写的代码:
str1:str1
str2:"blank"
str3:str3
str4:str4
最佳答案
试试这个:
str.Split('|')
如果不通过 StringSplitOptions.RemoveEmptyEntries
,它将按您的意愿工作。
关于C# 字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723499/