Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String Newline  RSS feed

 
Bruce Lee
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all how do I insert a newline at every 10 character with the condition it must be a space.

For eg.

Hi all, this is bruce lee. I'm still a novice in Java. Pls help in whatever you can.

to

Hi all,
this is
bruce lee.
I'm still
a novice
in Java.
Pls help
in
whatever
you can.

Anyone can help?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bruce Lee:
Hi all how do I insert a newline at every 10 character with the condition it must be a space.

For eg.

Hi all, this is bruce lee. I'm still a novice in Java. Pls help in whatever you can.

to

Hi all,
this is
bruce lee.
I'm still
a novice
in Java.
Pls help
in
whatever
you can.

Anyone can help?


One idea would be to convert your String to something mutable like StringBuffer or StringBuilder, and then use a simple loop to insert the newlines. Then convert it to a String.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've done paragraph wrapping like this in several langauges. If you don't have to preserve multiple spaces between words you can do something like:

That's a very high level sketch ... there are quite a few little details left out ... finding all the words, spaces between words, two spaces after a period, a single word that is longer than line max and so on. Does it seem to be the right direction?
 
Joe Zhou
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java world, char '\n' represents a new line.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joe Zhou:
In Java world, char '\n' represents a new line.


On Unix-based operating systems, anyway. On Windows, it's the "\r\n" sequence. But that's abstracted away by the system property "line.separator" (which is used by the BufferedWriter.newLine method).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!