C# string splitting
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
Try this one:
str.Split('|')
Without StringSplitOptions.RemoveEmptyEntries
passed, it'll work as you want.
this should do the trick...
string s = "str1||str3|str4";
string[] parts = s.Split('|');
The simplest way is to use Quantification:
using System.Text.RegularExpressions;
...
String [] parts = new Regex("[|]+").split("str1|str2|str3|srt4");
The "+" gets rid of it.
From Wikipedia : "+" The plus sign indicates that there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
Form msdn: The Regex.Split methods are similar to the String.Split method, except Split splits the string at a delimiter determined by a regular expression instead of a set of characters. The input string is split as many times as possible. If 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 done 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);
}
}
}
Try something like this:
string result = "str1||str3|srt4";
List<string> parsedResult = result.Split('|').Select(x => string.IsNullOrEmpty(x) ? "null" : x).ToList();
when using the Split()
the resulting string in the array will be empty (not null). In this example i have tested for it and replaced it with the actual word null
so you can see how to substitute in another value.
精彩评论