0

Let us say I have a long string

    String s1="This is my world. This has to be broken."

I am breaking the above string at a fixed interval of string length let's say when it's 10.

So the output I get after breaking is

    This is my
    world. Thi
    s has to b
    e broken.

Where as I want that the string should contain complete words and not broken words.

Just like this I want the output to be

    This is my
    world.
    This has 
    to be 
    broken.

How can I achieve the above output.

WISHY
  • 11,067
  • 25
  • 105
  • 197

3 Answers3

0

Try this:

String line = "element1 element2 element3";

String [] separatedList = line.split("\\s+");

for (String stringSeparated : separatedList) {
    System.out.println(stringSeparated);
}
Raider
  • 394
  • 1
  • 2
  • 26
0

I don't exactly understand the logic of the program, but you can use String.indexOf(' ') or something like that to know where exactly are the spaces of your string. check here http://www.tutorialspoint.com/java/java_string_indexof.htm and read the documentation http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)

Hagai
  • 678
  • 7
  • 20
0

Something along these lines?

int limit = 10;

// Tokenize words
String s1="This is my world. This has to be broken.";
final String[] words = s1.split( " " );

// Apply word-wrapping
final StringBuilder sb = new StringBuilder();
for( String word : words ) {
    if( sb.length() + word.length() > limit ) {
        // Next word wraps
        System.out.println( sb );
        sb.setLength( 0 );
    }
    else {
        // Otherwise add to current line
        if( sb.length() > 0 ) sb.append( ' ' );
    }
    sb.append( word );
}

// Handle final line
System.out.println( sb );
stridecolossus
  • 1,449
  • 10
  • 24