Given a sting, how can I skip the first x characters and then insert a value for every y characters?
For example:
“Lorem ipsum dolor sit amet,”
when skipping the first 10 caracters and then indsert “[here]” for every 3 caracters becomes:
“Lorem ipsu[here]m d[here]olo[here]r s[here]it [here]ame[here]t,”
What is the most efficient, fastest way of doing this in C#?
My current function looks like this but isn’t doing the skipping part, I know how to implement the skipping part but the technique used does not seem to be optimal:
public static string InsertHere(string source)
{
if (string.IsNullOrWhiteSpace(source))
{
return string.Empty;
}
int count = 0;
var sb = new StringBuilder();
foreach (char c in source)
{
count++;
sb.Append(c);
if (count == 10)
{
count = 0;
sb.Append(@"[here]");
}
}
return sb.ToString();
}
You’d have to profile them to see what’s best, but here’s my effort, I’ve gone for a string reader into a buffer approach.
Edit:
Fixed for edge cases source.Length < 10 or not whole multiple of 10 + 3*x. Also use just one buffer now.
Usage example: