拆分没有分隔符的字符串

时间:2011-09-08 07:35:29

标签: c# .net vb.net string c#-4.0

我有一个带变量的字符串变量     “abcdefghijklmnop”。

现在我想在右端的每个数组元素中将字符串拆分为字符串数组,其中包含3个字符(最后一个数组元素可能包含更少)。

即,
    “一”
    “BCD”
    “EFG”
    “HIJ”
    “荷航”
    “NOP”

最简单,最简单的方法是什么? (欢迎使用vb和C#代码)

4 个答案:

答案 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 :(得分: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"

(请不要使用此代码!这只是使用Regex + Linq时会发生什么的一个例子)

答案 2 :(得分: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";   

答案 3 :(得分:0)

好吧......我还有另一种方式......

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;
    }
相关问题