-1

如何拆分长字符串?

输入 :

ABCDEFGHI

输出 :

ABC, DEF, GHI
4

2 回答 2

0

假设这是一个很长的字符串,请使用字符串生成器进行连接。并使用 substring 来构建单独分组的字符串。这将为您节省内存。

string longString = "ABCDEFGHIJK";
int groupingLength = 3;

var stringLength = longString.Length;
var startingLength = Math.Min(longString.Length, groupingLength);
var startingString = longString.Substring(0, startingLength);
var sb = new StringBuilder(startingString);
if (stringLength > groupingLength)
{
    for(int i = groupingLength; i < stringLength; i = i + groupingLength)
    {
        var subStringLength = Math.Min(stringLength - i, groupingLength);
        var groupedString = longString.Substring(i, subStringLength);
        sb.Append(", ").Append(groupedString);
    }
}
var finalString = sb.ToString();
于 2012-05-19T01:58:40.983 回答
0

利用

string str = "ABCDEFGHI";

List<string> lst = new List<string>();

string temp = "";

for(int i = 0; i < str.Length; i++)
{
    temp = str[i].ToString();

    if((i + 1) % 3 == 0)
    {
        lst.Add(temp);
        temp = "";
    }
}

string final_str = string.Join(", ", lst);
于 2012-05-18T10:53:14.250 回答