将字符串拆分为多行?

时间:2014-05-02 05:22:29

标签: java string

我们假设我们有以下字符串:

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

如果字符串的长度超过30个字符,则需要对字符串进行细分,以使每行不超过30个字符。

分割后的输出应为:

  

"这是一个很长的字符串     ch需要被打破"

我知道我可以使用String.split(),但它并不符合我的要求。

分裂它的其他可能方法是什么?

4 个答案:

答案 0 :(得分:4)

使用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));

答案 1 :(得分:3)

您可以使用Apache-common的WordUtils.wrap()

可以用作

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

其中res将是

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

答案 2 :(得分:-2)

在swift中,在新行中创建大字符串或在多行中断。只需放\n。 它对我有用。

例如:"This string want to break from here then it shows like this"

然后只添加\ n(反斜杠n),不要添加""有这个。

现在

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

输出:

This string want to break from here

然后就像这样显示

希望它有所帮助。

答案 3 :(得分:-3)

了解" substring" &安培; "分裂"

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]);