开发者

Split a string without separator

I have a string variable with value "abcdefghijklmnop".

Now I want to split the string into string array with, say, three characters (the last array element may contain fewer) in each array element from the right end.

I.e.,

"a"

开发者_C百科 "bcd"

"efg"

"hij"

"klm"

"nop"

What is the easiest and simplest way to do this?? (Both Visual Basic and C# code is welcome)?


Here's a solution:

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

It gives the expected output of:

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


Here's something that works - wrapped up into a string extension function.

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

        }
    }
}

Usage:

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

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


Regex time!!

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 will contain:

"ab"
"cde"
"fgh"

(Please, don't use this code! It is only an example of what can happen when you use a regular expression + LINQ.)


Well... here is yet another way I arrived at:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜