问题
I have several delimiters. For example {del1, del2, del3 }. Suppose I have text : Text1 del1 text2 del2 text3 del3
I want to split string in such way:
- Text1 del1
- text2 del2
- text3 del3
I need to get array of strings, when every element of array is texti deli. How can I do this in C# ?
回答1:
String.Split
allows multiple split-delimeters. I don't know if that fits your question though.
Example :
String text = "Test;Test1:Test2#Test3";
var split = text.Split(';', ':', '#');
//split contains an array of "Test", "Test1", "Test2", "Test3"
Edit: you can use a regex to keep the delimeters.
String text = "Test;Test1:Test2#Test3";
var split = Regex.Split(text, @"(?<=[;:#])");
// contains "Test;", "Test1:", "Test2#","Test3"
回答2:
This should do the trick:
const string input = "text1-text2;text3-text4-text5;text6--";
const string matcher= "(-|;)";
string[] substrings = Regex.Split(input, matcher);
StringBuilder builder = new StringBuilder();
foreach (string entry in substrings)
{
builder.Append(entry);
}
Console.Out.WriteLine(builder.ToString());
note that you will receive empty strings in your substring array for the matches for the two '-';s at the end, you can choose to ignore or do what you like with those values.
回答3:
You could use a regex. For a string like this "text1;text2|text3^" you could use this:
(.*;|.*\||.*\^)
Just add more alternative pattens for each delimiter.
回答4:
If you want to keep the delimiter when splitting the string you can use the following:
string[] delimiters = { "del1", "del2", "del3" };
string input = "text1del1text2del2text3del3";
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for(int index = 0; index < parts.Length; index++)
{
string part = parts[index];
string temp = input.Substring(input.IndexOf(part) + part.Length);
foreach (string delimter in delimiters)
{
if ( temp.IndexOf(delimter) == 0)
{
parts[index] += delimter;
break;
}
}
}
parts
will then be:
[0] "text1del1"
[1] "text2del2"
[2] "text3del3"
回答5:
As @Matt Burland suggested, use Regex
List<string> values = new List<string>();
string s = "abc123;def456-hijk,";
Regex r = new Regex(@"(.*;|.*-|.*,)");
foreach(Match m in r.Matches(s))
values.Add(m.Value);
来源:https://stackoverflow.com/questions/9787904/how-to-split-string-that-delimiters-remain-in-the-end-of-result