Reputation: 43
How can I efficiently split a string with a character?
An example would be:
inputString = "ABCDEFGHIJ", sectionLength = 4, splitChar = '-', and output = "ABCD-EFGH-IJ"
Here is my first attempt: I wanted to split an input string with certain chars after every nth interval. I am wondering if there is a more efficient way to do this, or if I am missing something that could fail. I believe the If statement at the beginning should catch any invalid input, save null input.
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);
}
Upvotes: 0
Views: 91
Reputation: 150108
Strings in .NET are immutable. That means operations that combine strings end up creating a brand-new string.
This section of code
for (subStart = 0 ; (subStart + sectionLength) < end; subStart += sectionLength)
{
returnString = returnString + inputString.Substring(subStart, sectionLength) + splitChar;
}
keeps creating new strings.
Instead, explore the use of 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);
Doing your best to estimate the total length of the final string will reduce the number of buffer reallocations that StringBuilder does internally.
Upvotes: 3