Splitting strings in C #

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

But if I have a line: str1||str3|str4 output will be str1 str3 str4 . I want my result to be like str1 null/blank str3 str4 .

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" 

This is not what I am looking for. This is what I would like to code:

 str1:str1 str2:"blank" str3:str3 str4:str4 
+4
source share
4 answers

The easiest way is to use Quantification :

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

"+" gets rid of him.

From Wikipedia : "+" A plus sign means that there are one or more previous elements. For example, ab + c matches "abc", "abbc", "abbbc", etc., but not "ac".

The msdn form : Regex.Split methods are similar to the String.Split method, except that Split splits the string on a delimiter defined by a regular expression instead of a character set. The input string is broken as often as possible. If the pattern is not found in the input string, the return value contains one element whose value is the original input string.

Additional wish can be fulfilled with

 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
source

Try the following:

 str.Split('|') 

Without StringSplitOptions.RemoveEmptyEntries passed, it will work the way you want.

+9
source

this should do the trick ...

 string s = "str1||str3|str4"; string[] parts = s.Split('|'); 
+8
source

Try something like this:

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

when using Split() resulting string in the array will be empty (not empty). In this example, I tested it and replaced it with the actual word null so you can see how to replace it with a different value.

+1
source

All Articles