2010-11-29 126 views
0

我有字符串數組:幫助分割字符串

string[] data = new string[] {"1B", "2C", "01", "11", "3F", "5F", "02", "01", "06","12", "1C"}; 

需要找到一個「01」,然後找到「01」的下一個元素。複製它們之間有什麼,包括第一個 「01」,等我需要一個新的數組(或列表):

string[] arr; 
arr[0] = "01113F5F02"; 
arr[1] = "0106121C" 

OR

List<string> arr; 
arr[0] = "01113F5F02"; 
arr[1] = "0106121C" 

感謝。

+0

有超過列表中有一個「01」元素。你知道要分裂的元素的位置嗎? – 2010-11-29 12:14:55

+0

不,位置是未知的 – user348173 2010-11-29 12:15:45

回答

2

好了,因爲以前的答案是不恰當的,這裏的另一個嘗試:

public static List<string> SplitAndCombine(IEnumerable<string> source, 
              string delimiter) 
{ 
    List<string> result = new List<string>(); 
    StringBuilder current = null; 

    // Ignore anything before the first delimiter 
    foreach (string item in source.SkipWhile(x => x != delimiter)) 
    { 
     if (item == delimiter) 
     { 
      if (current != null) 
      { 
       result.Add(current.ToString()); 
      } 
      current = new StringBuilder(); 
     } 
     current.Append(item); 
    } 

    if (current != null) 
    { 
     result.Add(current.ToString()); 
    } 
    return result; 
} 
1
 string[] input = new string[] { "1B", "2C", "01", "11", "3F", "5F", "02", "01", "06", "12", "1C" }; 
     string splitStr = "01"; 
     int firstPos = 0; 
     for (int i = 0; i < input.Length; i++) 
     { 
      if (input[i] == splitStr) 
      { 
       firstPos = i; 
       break; 
      } 

     } 
     var data = input.Skip(firstPos).ToArray() ; 

     List<string> result = new List<string>(); 
     int index = -1; 
     string tmp = string.Empty; 
     while(++index < data.Length) 
     { 
      if(data[index] == splitStr && tmp != string.Empty) 
      { 
        result.Add(tmp); 
        tmp = string.Empty; 
      } 
      tmp += data[index]; 
      if(index == data.Length - 1 && tmp != string.Empty) 
       result.Add(tmp); 
     } 

     //results: 
     foreach (var x in result) 
     { 
      Console.WriteLine(x); 
     } 
1
public static List<string> SplitBy(string[] data, string splitStr) 
{ 
    var res = new List<string>(); 
    bool passedSplitStr = false; 
    var sb = new StringBuilder(); 
    for(int i = 0; i < data.Length; ++i) 
    { 
     if(data[i] == splitStr) 
     { 
      if(!passedSplitStr) 
      { 
       passedSplitStr = true; 
      } 
      else 
      { 
       res.Add(sb.ToString()); 
       sb.Clear(); 
      } 
      sb.Append(data[i]); 
     } 
     else 
     { 
      if(passedSplitStr) 
       sb.Append(data[i]); 
     } 
    } 
    if(sb.Length != 0) 
     res.Add(sb.ToString()); 
    return res; 
} 

用法:

var arr = SplitBy(data, "01"); 
1
string[] data = new string[] { "1B", "2C", "01", "11", "3F", "5F", "02", "01", "06", "12", "1C" }; 
var res = string.Join(" ", data).Split(new string[] {" 01 "}, StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(x=>"01" + x.Replace(" ","")).ToArray();