Java实现字符串输出的方法
以下程序可以输出如:
aaa
aab
aac
......
aba
abb
......
edd
ede
edf
......
zzx
zzy
zzz
的连续字符串。
修改START_STRING和END_STRING,也可以输出任意位数的连续字符串,可用于穷举遍历。
importjava.io.*;
/**
*@authorcomstep
*@websitehttp://blog.csdn.net/comstep
*/
publicclassAToZ
{
privateStringstr="";
privateintlength=0;
privatechar[]ch;
publicAToZ(Stringstr)
{
this.str=str;
this.length=str.length();
this.ch=str.toCharArray();
}
publicStringgetNextString()
{
for(inti=0,j=length-1;i<length&&j>=0;i++)
{
if(ch[j]!='z')
{
ch[j]++;
break;
}
else
{
ch[j]='a';
j--;
continue;
}
}
returnnewString(ch);
}
publicstaticvoidmain(String[]args)throwsException
{
StringSTART_STRING="aaa";
StringEND_STRING="zzz";
AToZaTOz=newAToZ(START_STRING);
FileOutputStreamfout=newFileOutputStream("out.txt");
PrintWriterprintWriter=newPrintWriter(fout);
printWriter.println(START_STRING);
intcount=1;
while(true)
{
START_STRING=aTOz.getNextString();
printWriter.println(START_STRING);
System.out.println(START_STRING);
count++;
if(START_STRING.equals(END_STRING))
break;
}
printWriter.println("共:"+count+"个");
System.out.println("共:"+count+"个");
printWriter.close();
fout.close();
}
}
/**
*@authorcomstep
*@websitehttp://blog.csdn.net/comstep
*/
publicclassAToZ
{
privateStringstr="";
privateintlength=0;
privatechar[]ch;
publicAToZ(Stringstr)
{
this.str=str;
this.length=str.length();
this.ch=str.toCharArray();
}
publicStringgetNextString()
{
for(inti=0,j=length-1;i<length&&j>=0;i++)
{
if(ch[j]!='z')
{
ch[j]++;
break;
}
else
{
ch[j]='a';
j--;
continue;
}
}
returnnewString(ch);
}
publicstaticvoidmain(String[]args)throwsException
{
StringSTART_STRING="aaa";
StringEND_STRING="zzz";
AToZaTOz=newAToZ(START_STRING);
FileOutputStreamfout=newFileOutputStream("out.txt");
PrintWriterprintWriter=newPrintWriter(fout);
printWriter.println(START_STRING);
intcount=1;
while(true)
{
START_STRING=aTOz.getNextString();
printWriter.println(START_STRING);
System.out.println(START_STRING);
count++;
if(START_STRING.equals(END_STRING))
break;
}
printWriter.println("共:"+count+"个");
System.out.println("共:"+count+"个");
printWriter.close();
fout.close();
}
}
本文地址:http://www.45fan.com/a/question/73986.html