Zaki
Zaki

Reputation: 5600

split string and insert break line

I have a string of say 2000 characters how can I split the screen into 70 characters and insert newline for each 70 lines I have tried for first 70 characters and works fine as follow :

Dim notes As String = ""
        If (clmAck.Notes.Count > 70) Then
            notes = clmAck.Notes.Insert(70, Environment.NewLine)
        Else

Upvotes: 0

Views: 256

Answers (2)

user27414
user27414

Reputation:

It's C#, but should be easy to translate:

string notes = "";
var lines = new StringBuilder();

while (notes.Length > 0)
{
    int length = Math.Min(notes.Length, 70);
    lines.AppendLine(notes.Substring(0, length));

    notes = notes.Remove(0, length);
}

notes = lines.ToString();

Upvotes: 1

Johan Larsson
Johan Larsson

Reputation: 17580

I wrote this now for fun:

public static class StringExtension
{
    public static string InsertSpaced(this string stringToinsertInto, int spacing, string stringToInsert)
    {
        StringBuilder stringBuilder = new StringBuilder(stringToinsertInto);
        int i = 0;
        while (i + spacing < stringBuilder.Length)
        {
            stringBuilder.Insert(i + spacing, stringToInsert);
            i += spacing + stringToInsert.Length;
        }
        return stringBuilder.ToString();
    }
}

[TestCase("123456789")]
public void InsertNewLinesTest(string arg)
{
    Console.WriteLine(arg.InsertSpaced(2,Environment.NewLine));
}

Upvotes: 2

Related Questions