C#字符串分割

4
如果我有一个字符串: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

3
你应该查一下StringSplitOptions.RemoveEmptyEntries标志的作用。 - Matthew Iselin
4个回答

9
尝试这个:
str.Split('|')

如果没有传递 StringSplitOptions.RemoveEmptyEntries,它将按照您想要的方式工作。


我误读了问题,我以为OP想要的是他不想要的..哈哈,抱歉。现在我的投票功能被SO锁定了,但8分钟后我会把投票从踩改为赞。:) - Cheng Chen
SO 告诉我:“您在 14 分钟前对此答案投过票,除非此答案被编辑,否则您的投票现已锁定”。那么,除非您编辑答案,我将无法对您的答案进行投票?对我的错误感到抱歉。 - Cheng Chen

8
这应该可以解决问题...
string s = "str1||str3|str4";
string[] parts = s.Split('|');

4

最简单的方法是使用量化

using System.Text.RegularExpressions;
...
String [] parts = new Regex("[|]+").split("str1|str2|str3|srt4");

“+”可以消除它。

来自维基百科: “+”加号表示前面的元素有一个或多个。例如,ab+c匹配“abc”、“abbc”、“abbbc”等,但不匹配“ac”。

来自msdn: Regex.Split方法与String.Split方法类似,但是Split根据正则表达式而不是字符集拆分字符串。输入字符串尽可能多次地被拆分。如果在输入字符串中找不到模式,则返回值包含一个元素,其值为原始输入字符串。

可以使用以下附加愿望:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
    class Program{
        static void Main(string[] args){
            String[] parts = "str1||str2|str3".Replace(@"||", "|\"blank\"|").Split(@"|");

            foreach (string s in parts)
                Console.WriteLine(s);
        }
    }
}

4
使用Regex可能是一种"酷"的方式,但这是对所提出问题的一个非常迂回的解决方案。原帖作者只是想保留空段落,而Split函数默认情况下会实现这一点--除非您传递了StringSplitOptions.RemoveEmptyEntries选项。因此,原帖作者可以通过简单地从原始示例代码中的Split调用中删除不需要的选项来解决原始问题。构建和编译正则表达式比这种情况所需的开销(和复杂性)要大得多。 - Lee

1

可以尝试这样做:

string result = "str1||str3|srt4";
List<string> parsedResult = result.Split('|').Select(x => string.IsNullOrEmpty(x) ? "null" : x).ToList();

使用Split()函数时,数组中的结果字符串将为空(而不是null)。在这个例子中,我已经测试过它并用实际单词null替换了它,这样你就可以看到如何用另一个值进行替换。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接