当前位置:网站首页>字符串反转方法总结

字符串反转方法总结

2022-06-09 08:25:00 源氏不可挡

1.利用StringBuilder的reverse方法

import java.util.*;
import java.io.*;
public class Main{
    
    public static void main(String[] args) throws IOException{
    
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String str=br.readLine();
        StringBuilder sbtr=new StringBuilder(str);
        sbtr.reverse();
        System.out.println(sbtr.toString());
    }
}

2.利用栈的先进后出

public class Main{
    
    public static void main(String[] args) {
    
        Stack stack = new Stack();
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        for (int i = 0; i <s.trim().length() ; i++) {
    
            stack.push(s.charAt(i));
        }
        while(!stack.empty()){
    
            System.out.print(stack.pop());
        }
    }
}

3.倒序遍历字符串

public class Main {
    
    public static void main(String[] args) {
    
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        for (int i = s.length()-1; i >=0 ; i--) {
    
            System.out.print(s.charAt(i));
        }
    }
}
原网站

版权声明
本文为[源氏不可挡]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_50083902/article/details/125094986