用java实现:现在有一个很长的标题,我要实现的是在指定长度处换行

2024-12-19 21:42:26
推荐回答(5个)
回答1:

给你个简单的:

class C {
  public static void main(String[] args) {
    String s = "卡带机分开九发股份脚后跟恋风恋歌看过大夫";
    for (int i = 0; i < s.length(); i += 5)
      System.out.println(s.substring(i, i + 5));
  }
}

回答2:

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
String str = "卡带机分开九发股份脚后跟恋风恋歌看过大夫";
while (str.length()> 5){
System.out.println(str.substring(0,5));
str = str.substring(5);
}
if(str.length() <= 5 ){
System.out.println(str);
}

}

}

回答3:

看下吧 很简单的
public class Z {

public static void main(String[] args) {
String s="卡带机分开九发股份脚后跟恋风恋歌看过大夫";
int start =0;
int end=5;
while(true){
System.out.println(s.substring(start, end));
start=end;
end +=5;
if(end>s.length()) break;
}
}
}

回答4:

//完全按照你的要求写的
import java.io.*;
public class WrapLine {
public static void main(String args[]){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("输入一串字符串");
String s = br.readLine();
char[]c = s.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
count ++;
if(count%5==0){
System.out.print(c[i]+"\r");
}else{
System.out.print(c[i]+"");
}
}
} catch (IOException e) {
e.printStackTrace();
}

}

}

回答5:

//用JAVA做事当然首先用对象来做
//所以写了个StringRebuilder的类来解决楼主问题

public class StringRebuilder {
private static final String rn = "\r\n";//换行符
private StringBuffer buff ;//用StringBuffer的目的就是为了使操作超长的数据提高效率

public StringRebuilder(String src){
this.buff=new StringBuffer(src);
}
//根据长度重排
public StringBuffer doRebuild(int len){
StringBuffer tmp = new StringBuffer();
while(buff.length()>len){
tmp.append(buff.subSequence(0,len)+rn);
buff.delete(0,len);
}
tmp.append(buff);
return tmp;
}

public static void main(String[] args){
String test = "卡带机分开九发股份脚后跟恋风恋歌看过大夫";
int len =5;//长度自己决定
StringRebuilder sr = new StringRebuilder(test);
String out = sr.doRebuild(len).toString();
System.out.println(out);
}
}