views:

44

answers:

2

I have a string with 100 characters and it is for me too long in one line. I want to make NewLine after each 25 characters. For example:

Instead: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."

Just a:

"Lorem ipsum dolor sit amet,

consetetur sadipscing elitr,

sed diam nonumy eirmod tempor..."

Which method can I use to do that?

Thanks for a help and take care, Ragims

+1  A: 

Use the String.Substring(Start, Length) overload.

Loop from Start = 0 taking Length = 25 each time until you have less than 25 characters remaining and then take the remainder as your last item.

The following code illustrates the algorithm, though it's by no means optimal.

int start = 0;
int length = 25;  // so it can be configurable
int amountLeft = myString.Length;

while (start + length <= myString.Length)
{
    Console.WriteLine(myString.Substring(start, length));  // In lieu of your action
    start += length;
    amountLeft -= length;
}

if (amountLeft > 0)
{
    Console.WriteLine(myString.Substring(start, amountLeft));
}
ChrisF
+3  A: 

You can use a regular expression:

s = Regex.Replace(s, "(.{25})", "$1<br/>");
Guffa
greate! thank you
Ragims