java中平均截取字符串

有字符串str,长度未知,平均截取此字符串,分行显示,每次最大截100个,分行显示。
假设字符串301个字节,就显示4行,前3行100个 最后1行1个
假设字符串300个字节,就显示3行。

String str = "dsfffffffff" ; //多长都行
int len = str.length() ;
int begin = 0 ; //记录从第几位开始截取
int end = 0 ; //记录截取到第几位
int a = 1 ; //记录第几次截取
while(begin < len) {
if((100*a) > str.length()) {
end = len ;
} else {
if(len > 100) {
end = 100 * a;
}else {
end = len ;
}
}
System.out.println(str.substring(begin, end));
if(len > 100) {
begin = 100 * a;
} else {
begin = len ;
}
a++ ;
}

贴main方法里就能用。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-05-21
交谈中请勿轻信汇款、中奖信息,勿轻易拨打陌生电话。

龙虾 上午 11:25:27
public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="kalfldj23sjdkljksdjkl34444d4444jksdjkljldjl;as90990";
double a=str.length();
double b=10;
double times=Math.ceil(a/b);
for(int i=0;i<(int)times;i++)
{
int last=(int)times-1;

if(i<last)
{
int start=(int)(b*i);
int end=(int)(b*(i+1));
System.out.println(str.substring(start,end));
}else
{
int start=(int)(b*i);
System.out.println(str.substring(start));
}
}

}
}
第2个回答  2010-05-21
public static void main(String [] args)
{
String str="";
int v=100;
for(int i=0;i<str.length();i++)
{
System.out.print(str.substring(i,i+1));
if(i==v)
{
System.out.println();//有一百个字符就换行
v+=100;
}

}
}
第3个回答  2010-05-21
public class CharCut {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int temp = sc.nextInt();
int length = str.length();
if(length%temp==0){
int total = length/temp;
String[] result = new String[total];
int beginIndex = 0;
int endIndex = 0;
for(int i=0;i<total;i++){
endIndex += temp;
result[i] = str.substring(beginIndex, endIndex);
beginIndex += temp;
System.out.println(result[i]);
}
}else{
int total = length/temp+1;
String[] result = new String[total];
int beginIndex = 0;
int endIndex = 0;
for(int i=0;i<total;i++){
if(i==total-1){
endIndex += length%temp;
result[i] = str.substring(beginIndex, endIndex);
beginIndex += temp;
System.out.println(result[i]);
}else{
endIndex += temp;
result[i] = str.substring(beginIndex, endIndex);
beginIndex += temp;
System.out.println(result[i]);
}
}
}
}
}

你自己输入字符串和每次要截取的字符串数目!