用C#字符拆分字符串
本文关键字:字符串 拆分 字符 | 更新日期: 2023-09-27 17:59:07
如何有效地用一个字符拆分字符串?
例如:
inputString="ABCDEFGHIJ",sectionLength=4,splitChar='-',output="ABCD-EFGH-IJ"
这是我的第一次尝试:我想在每第n个间隔后分割一个带有特定字符的输入字符串。我想知道是否有更有效的方法来做到这一点,或者我是否错过了一些可能失败的东西。我认为开头的If语句应该捕获任何无效输入,保存null输入。
public String SplitString(string inputString, int sectionLength,
char splitChar)
{
if (inputString.Length <= sectionLength || sectionLength < 1)
return inputString;
string returnString = "";
int subStart;
int end = inputString.Length;
for (subStart = 0 ; (subStart + sectionLength) < end;
subStart += sectionLength)
{
returnString = returnString +
inputString.Substring(subStart,
sectionLength) + splitChar;
}
return returnString + inputString.Substring(subStart,
end - subStart);
}
.NET中的字符串是不可变的。这意味着组合字符串的操作最终会创建一个全新的字符串。
这部分代码
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
returnString = returnString + inputString.Substring(subStart, sectionLength) + splitChar;
}
不断创建新字符串。
相反,探索StringBuilder的使用。
int estimatedFinalStringLength = 100; // <-- Your estimate here
StringBuilder returnString = new StringBuilder(estimatedFinalStringLength);
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
returnString.Append(inputString.Substring(subStart, sectionLength) + splitChar);
}
return returnString.ToString() + inputString.Substring(subStart, end - subStart);
尽最大努力估计最终字符串的总长度将减少StringBuilder在内部进行的缓冲区重新分配的数量。