Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C#: How do you split a string after a specific length and after a whitespace?

This might be a really dumb question for some of you, but I just don't seem to get this right: I want to divide a long string into some lines of text. Therefore I need to split it after a specific length. As the words should be complete in one line it should also take care of the whitespaces. And there's the problem!

This is my code:

for(x=0; x<Text.Length; x+=CharsInOneLine)

{

if( !(x+CharsInOneLine > Text.Length) )

{

StringArray[ x / CharsInOneLine ] = Text.Substring (x , CharsInOneLine);

}

}

else

[...]

This code correctly splits the string into parts. But of course it does not take care of the whitespaces. And: No, I can't use \r\n to create a new line. It does not work in this specific case.

Can anyone of you help?

1 Answer

Relevance
  • 1 decade ago
    Favorite Answer

    If your string can't be longer than say 80 characters, go to character 80 and if it isn't a space have your program check character 79 and keep going back until you have a space and then split the the string.

Still have questions? Get your answers by asking now.