2011-09-08 93 views
3

我有一個字符串變量,其值爲 「abcdefghijklmnop」。

拆分沒有分隔符的字符串

現在我要拆分的字符串轉換成字符串數組與說3個字符(最後一個數組元素可以包含以下)從右側端的每個數組元素。

即,
「一」
「BCD」
「EFG」
「HIJ」
「荷航」
「NOP」

什麼是最簡單,最簡單的如何做到這一點? (歡迎使用vb和C#代碼)

+0

對不起,我顯然不能今天看了。 –

回答

4

這裏的一個解決方案:

var input = "abcdefghijklmnop"; 
var result = new List<string>(); 
int incompleteGroupLength = input.Length % 3; 
if (incompleteGroupLength > 0) 
    result.Add(input.Substring(0, incompleteGroupLength)); 
for (int i = incompleteGroupLength; i < input.Length; i+=3) 
{ 
    result.Add(input.Substring(i,3)); 
} 

給出的預期輸出:

"a" 
"bcd" 
"efg" 
"hij" 
"klm" 
"nop" 
1

正則表達式時間!

Regex rx = new Regex("^(.{1,2})??(.{3})*$"); 

var matches = rx.Matches("abcdefgh"); 

var pieces = matches[0].Groups[1].Captures.OfType<Capture>().Select(p => p.Value).Concat(matches[0].Groups[2].Captures.OfType<Capture>().Select(p => p.Value)).ToArray(); 

片將包含:

"ab" 
"cde" 
"fgh" 

(請不要使用此代碼只有當你使用正則表達式+ LINQ的什麼都有可能發生的例子!)

1

下面是一些工作 - 包裝成一個字符串擴展功能。

namespace System 
{ 
    public static class StringExts 
    { 
     public static IEnumerable<string> ReverseCut(this string txt, int cutSize) 
     { 
      int first = txt.Length % cutSize; 
      int taken = 0; 

      string nextResult = new String(txt.Take(first).ToArray()); 
      taken += first; 
      do 
      { 
       if (nextResult.Length > 0) 
        yield return nextResult; 

       nextResult = new String(txt.Skip(taken).Take(cutSize).ToArray()); 
       taken += cutSize; 
      } while (nextResult.Length == cutSize); 

     } 
    } 
} 

用法:

  textBox2.Text = ""; 
      var txt = textBox1.Text; 

      foreach (string s in txt.ReverseCut(3)) 
       textBox2.Text += s + "\r\n"; 
0

well..here是另一種方式,我來到..

private string[] splitIntoAry(string str) 
    { 
     string[] temp = new string[(int)Math.Ceiling((double)str.Length/3)]; 
     while (str != string.Empty) 
     { 
      temp[(int)Math.Ceiling((double)str.Length/3) - 1] = str.Substring(str.Length - Math.Min(str.Length, 3)); 
      str = str.Substring(0, str.Length - Math.Min(str.Length, 3)); 
     } 
     return temp; 
    } 
相關問題