我需要一个“变量序列”分割字符串..
分割字符串开始和结束字符
例如,我有这个字符串:
string myString="|1 Test 1|This my first line.|2 Test 2|This is my second line";
我需要得到一个字符串排列:
这是我的第一行
这是我的第二行。
而在同一时间,最好的最好的将得到这个:
| 1 Test1 |
这是我的第一行
| 2 Test2 |
这是我的第二行。
任何帮助?
我需要一个“变量序列”分割字符串..
分割字符串开始和结束字符
例如,我有这个字符串:
string myString="|1 Test 1|This my first line.|2 Test 2|This is my second line";
我需要得到一个字符串排列:
这是我的第一行
这是我的第二行。
而在同一时间,最好的最好的将得到这个:
| 1 Test1 |
这是我的第一行
| 2 Test2 |
这是我的第二行。
任何帮助?
您可以使用正则表达式来拆分字符串,例如
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);
}
只是丢弃的第一项(因为这将是空白)
string.Split with |作为参数,并为子字符串如果string.StartsWith一个数字和string.EndsWidth一个数字加|开始和结束。这有帮助吗?
string[] myStrings = myString.Split('|');
这会给你一个4单元阵列,其中包括:
1 Test 1
This is my first line.
2 Test 2
This is my second line.
从那里,我想你会被迫通过数组中的元素进行迭代,并确定行动的适当过程对于基于当前元素内容的元素。
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]);
}
}
使用LINQ,你可以做这样的:
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;
}
}
与分割字符串 '|'并手动添加它们看起来像是最好的策略。
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] + "|";
}
}
我谢谢你..它是完美的..我谢谢大家家伙... – Stan92