Reputation: 453
I need to split a string with a "variable sequence"..
For example, I have this string :
string myString="|1 Test 1|This my first line.|2 Test 2|This is my second line";
I need to get an array of strings with :
This is my first line
This is my second line.
And in the same time, the best of the best would be to get this:
|1 Test1|
This is my first line
|2 Test2|
This is my second line.
Any help?
Upvotes: 2
Views: 18312
Reputation: 82096
You could use a regular expression to split the string e.g.
string str = "|1 Test 1|This is my first line.|2 Test 2|This is my second line.";
var pattern = @"(\|(?:.*?)\|)";
foreach (var m in System.Text.RegularExpressions.Regex.Split(str, pattern))
{
Console.WriteLine(m);
}
Just discard the first entry (as it will be blank)
Upvotes: 5
Reputation: 670
Split the string with '|' and add them in manually seems like the best strategy.
string s = "|test1|This is a string|test2|this is a string";
string[] tokens = s.Split(new char[] { '|' });
string x = "";
for (int i = 0; i < tokens.Length; i++)
{
if (i % 2 == 0 && tokens[i].Length > 0)
{
x += "\n" + tokens[i] + "\n";
}
else if(tokens[i].Length > 0)
{
x += "|" + tokens[i] + "|";
}
}
Upvotes: 0
Reputation: 3431
Using LINQ you can do it like this:
public IEnumerable<string> GetLines(string input)
{
foreach (var line in input.Split(new [] {'|' }, StringSplitOptions.RemoveEmptyEntries))
{
if (Char.IsDigit(line[0]) && Char.IsDigit(line[line.Length - 1]))
yield return "|" + line + "|";
yield return line;
}
}
Upvotes: 1
Reputation: 10967
string myString = "|1 Test 1|This my first line.|2 Test 2|This is my second line";
string[] mainArray = myString.Split('|');
String str = "";
List<string> firstList = new List<string>();
List<string> secondList = new List<string>();
for (int i = 1; i < mainArray.Length; i++)
{
if ((i % 2) == 0)
{
str += "\n|" + mainArray[i];
firstList.Add(mainArray[i]);
}
else
{
str += "\n|" + mainArray[i] + "|";
secondList.Add(mainArray[i]);
}
}
Upvotes: 0
Reputation: 7138
string[] myStrings = myString.Split('|');
This will give you a 4 element array consisting of:
1 Test 1
This is my first line.
2 Test 2
This is my second line.
From there, I think you'll be forced to iterate through the elements of the array and determine the proper course of action for the element that follows based on the contents of the current element.
Upvotes: 1
Reputation: 3678
string.Split with | as parameter and for the substrings if string.StartsWith a number and string.EndsWidth a number add | to start and end. is that helpful enough?
Upvotes: 2