如何分割长字符串?
输入:
ABCDEFGHI
输出:
ABC, DEF, GHI
答案 0 :(得分: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);
答案 1 :(得分: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();