我需要一個「變量序列」分割字符串..
分割字符串開始和結束字符
例如,我有這個字符串:
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