例子,三种不同方法实现字符串反转。
复制代码 代码示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reverse {
public static void main(String[] args) throws IOException
{
String str;
BufferedReader bufReader = new BufferedReader(
new InputStreamReader(System.in));
System.out.print("请输入字符串:");
str = bufReader.readLine();
char[] ch = str.toCharArray();
char[]b;
b = new char[ch.length];
for(int i=0; i<ch.length;i++)
{
b[i] = ch[ch.length-1-i];
}
for(int i=0; i<b.length; i++)
{
System.out.print(b[i]);
}
/*就地逆置
chartemp;
for(inti=0;i<ch.length/2;i++)
{
temp=ch[i];
ch[i]=ch[ch.length-1-i];
ch[ch.length-1-i]=temp;
}
for(inti=0;i<ch.length;i++)
{
System.out.print(ch[i]);
}*/
/*利用栈来实现
Stackst=newStack();
for(inti=0;i<ch.length;i++)
{
st.push(ch[i]);
}
for(inti=0;i<ch.length;i++)
{
System.out.println(st.pop());
}*/
}
}
例2,字符串反转程序,其中两个函数实现的结果不同:
复制代码 代码示例:
public class Reverse2 {
static String str = "I am a student";
public static void main(String []args){
back1();
back2();
}
public static void back1(){
String []str2 = str.split(" ");
for(int i=str2.length-1;i>=0;i--){
System.out.println(str2[i]+" ");
}
}
public static void back2(){
char []c = str.toCharArray();
char []temp = new char[c.length];
for(int i=0,j=c.length-1;i<c.length;i++,j--){
temp[j]=c[i];
}
System.out.println(temp);
}
}