将字符串拆分为组

时间:2013-11-19 11:41:18

标签: c#

如果邮件超过160个字符,我将需要以153个字符的组显示邮件。

因此161 char字符串应该显示在两个组中(一个组有153个字符,另一个组有8个字符)。我该怎么做?

string message = "0123456789";//10char string
//string message = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";//161char string
int parts = (message.Length <= 160) ? 1 : ((message.Length + 152) / 153);
for (int x = 1; x <= parts; x++)
{                                            
    Console.WriteLine("this Msg Part: " + x.ToString());
    Console.WriteLine("this Msg Part Text:" + "//messgae part text goes here...");
    Console.WriteLine("Total Msg Parts: " + parts.ToString());
}

3 个答案:

答案 0 :(得分:2)

string message = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";//161char string
int groupCount = 153;

IEnumerable<string> groups = message.Select((c, index) => new{ c, index })
            .GroupBy(x => x.index / groupCount)
            .Select(xg => string.Join("", xg.Select(x => x.c)));

foreach(string str in groups)
    Console.WriteLine(str);

打印:

"012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012" 
"34567890"

答案 1 :(得分:1)

考虑以下代码......

        string message = "0123456789";//10char string
        //string message = "01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";//161char string
        int parts = (message.Length/ 153) + (message.Length % 153 > 0 ? 1 : 0);
        for (int x = 1; x <= parts; x++)
        {
            Console.WriteLine("this Msg Part: " + x.ToString());
            Console.WriteLine("this Msg Part Text:" + message.Substring( (x-1)* 153, message.Length < ((x-1)* 153 + 153) ? message.Length - (x-1)* 153 : 153));
            Console.WriteLine("Total Msg Parts: " + parts.ToString());
        }

祝你好运!

答案 2 :(得分:0)

更改您的主线

Console.WriteLine("this Msg Part Text:" + message.Substring(((x-1)*153),(parts == x )? message.Length-(153*(x-1)) : 153*x));

希望这会有所帮助......