2014-06-19 26 views
-3

HI字符串我有一個這樣的字符串:C#如何拆分包含數字陣列

string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black"; 

我想拆分字符串,把陣列中的像這樣:

1 Hello World 
2 I'm a newbie 
33 The sun is big 
176 The cat is black 

結果可以在一個字符串[],ArrayList中,列表或LINQ

添加了什麼我試過,但它不工作..

ArrayList oArrayList = new ArrayList(); 
Regex oRegex = new Regex(@"\d+"); 
Match oMatch = oRegex.Match(test); 
int last = 0; 

while (oRegex.Match(test).Success) 
{ 
    oArrayList.Add(oMatch.Value + " " + test.Substring(last, oMatch.Index)); 
    last = oMatch.Index; 
    test = test.Remove(0, oMatch.Index); 
    oMatch = oRegex.Match(test); 
} 
+2

我希望你喜歡正則表達式,因爲我有一種感覺有些會很快顯示出來...... – BradleyDotNET

+0

「結果可能在String [],ArrayList,List或Linq中」聽起來像一個作業問題 – lahsrah

+0

可能不是也可能是「如何解析'node.InnerXml'(ToString()'的一些其他定義良好的格式/對象樹)結果的XY問題。 –

回答

0

嘗試這種情況:

string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black"; 

Regex regexObj = new Regex(@"(\d+)([^0-9]+)", RegexOptions.IgnoreCase); 
Match match = regexObj.Match(test); 
while (match.Success) 
{ 
    string numPart = match.Group[1].Value; 
    string strPart = match.Group[2].Value; 
    match = match.NextMatch(); 
} 

輸出:

Regex Output

+0

我試過這個解決方案,它的工作! –

0

相當簡單是誠實

string test = "1Hello World 2I'm a newbie 33The sun is big 176The cat is black"; 
var tmp = Regex.Split(test,@"\s(?=\d)"); 

TMP將是一個字符串數組

+0

不錯的選擇,但在結果之間沒有空格之間的小數和以下文本 –

+0

其捕獲小數點前的空格。你甚至嘗試在示例控制檯應用程序中運行它嗎?如果你想要空間或小數點前沒有空格,你可以稍微修改一下regex來得到你想要的,但這是最簡單的方法。 – user3754372

0

鑑於輸入字符串test,則可以使用Regex.Split在小數邊界上拆分字符串。添加每個元素的數量和文本之間的空間需要每個元素調用Regex.Match以獲得所需的格式:

var r = Regex.Split(test, @"(?<=\D)(?=\d)") // split at each boundary 
              // between a non-digit (\D) 
              // and digit (\d). 
      .Select(a=>Regex.Match(a, @"(\d+)(.*)").Result("$1 $2")); 
              //^insert a space between 
              // decimal and following text 

結果是IEnumerable<string>根據需要在LINQ的可被處理。