WISHY
WISHY

Reputation: 11999

Splitting a string over multiple lines?

Let us suppose we have the following string:

String s1 = "This is a very long string which needs to be broken"

If the string's length is more than 30 characters, the string needs to be broken down so that each line should not contain more than 30 characters.

After splitting the output should be:

"This is a very long string whi
ch needs to be broken"

I know I can use String.split(), but it doesn't suit my requirement.

What are the other possible ways to split it?

Upvotes: 1

Views: 1739

Answers (4)

malu
malu

Reputation: 1

In swift , to make large string as in new line or break in multiple lines.Just put \n. It worked for me.

For example : "This string want to break from here then it shows like this"

then just add \n (back slash n) only, do not add "" with this.

Now

"This string want to break from here **\n** then it shows like this"

output :

This string want to break from here

then it shows like this

Hope it helps someone.

Upvotes: -2

HelloWorld123456789
HelloWorld123456789

Reputation: 5359

Use substring().

String str = "This is a very long string which needs to be broken";
int begin=0;
int end=str.length();
int lengthToWrap = 30;

while (str.length() > lengthToWrap) {
    System.out.println(str.substring(begin,begin+lengthToWrap));
    str=str.substring(begin+lengthToWrap,end);
    end=end-lengthToWrap;
}

System.out.println(str.substring(begin,end));

Upvotes: 5

Scary Wombat
Scary Wombat

Reputation: 44813

You can use Apache-common's WordUtils.wrap().

It can be used as

String res = WordUtils.wrap ("This is a very long string which needs to be broken", 30);

where res will be

This is a very long string\r\nwhich needs to be broken

Upvotes: 3

Ninja
Ninja

Reputation: 183

Read about "substring" & "split"

System.out.print(input.substring(0,7)+"\n"+input.substring(8,25)+"\n"+input.substring(27,51));

OR

String[] words = input.split(" ");
   System.out.print(words[0]+" "+words[1]+"\n"+words[2]+" "+words[3]+" "+words[4]+" "+words[5]+"\n"+words[6]+" "+words[7]+" "+words[8]+" "+words[9]+" "+words[10]);

Upvotes: -3

Related Questions