Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string splitting

Tags:

string

c#

If I have a string: str1|str2|str3|srt4 and parse it with | as a delimiter. My output would be str1 str2 str3 str4.

But if I have a string: str1||str3|str4 output would be str1 str3 str4. What I'm looking for my output to be like is str1 null/blank str3 str4.

I hope this makes sense.

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]);
    }
}

Output

str1:str1
str2:str3
str3:str4
str4:"blank"

Thats not what i'm looking for. This is what I would like to code:

str1:str1
str2:"blank"
str3:str3
str4:str4
like image 837
AAH-Shoot Avatar asked Nov 30 '22 05:11

AAH-Shoot


1 Answers

Try this one:

str.Split('|')

Without StringSplitOptions.RemoveEmptyEntries passed, it'll work as you want.

like image 112
mmx Avatar answered Dec 16 '22 21:12

mmx