分割没有分隔符的字符串

3
我有一个字符串变量,其值为“abcdefghijklmnop”。
现在我想将该字符串从右侧每三个字符分割成一个字符串数组(最后一个数组元素可能包含较少的字符)。
例如: "a" "bcd" "efg" "hij" "klm" "nop"
请问最简单和最易懂的方法是什么?(欢迎使用Visual Basic或C#代码)
4个回答

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();

pieces 将包含:

"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

好的...这里是我到达的另一种方法:

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接