HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Better way to write a string slicer

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wayslicerwritebetterstring

Problem

Here is some code to insert a new line escape sequence after a certain number of characters (for fixed width displays)

private string spliceNoteText(string text)
    {
        StringBuilder sb = new StringBuilder();

        int maxWidth = 70;
        int blockOfText;

        for (int i = 0; i = text.Length)
                continue;

            int charsRemaining = text.Length - i;

            if (charsRemaining <= maxWidth)
                blockOfText = charsRemaining;
            else
                blockOfText = maxWidth;

            sb.Append(text.Substring(i, blockOfText));
            sb.Append("\n");

        }
        return sb.ToString();
    }


It's is ugly and boring, can it be made prettier or more elegant?

Solution

You can make it reusable by taking a line length parameter, and you can use a regular expression to reduce the code somewhat:

public static string SpliceNoteText(string text, int lineLength) {
  return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}


Note that I used Environment.NewLine which gives the newline character combination for the current system, instead of the newline character escape sequence. That's what you would normally do, but it might not apply in your specific case, depending on how you are going to use the string.
Edit:

The regular expression is of course not as fast as the original code. A simple performance test for splicing a 100000 character string gives:

Original  0,23 ms.
Regexp    1,31 ms.
Insert   15,06 ms.

Code Snippets

public static string SpliceNoteText(string text, int lineLength) {
  return Regex.Replace(text, "(.{" + lineLength + "})", "$1" + Environment.NewLine);
}
Original  0,23 ms.
Regexp    1,31 ms.
Insert   15,06 ms.

Context

StackExchange Code Review Q#5283, answer score: 4

Revisions (0)

No revisions yet.