Java倒序输出字符串和倒序输出句子的几种办法

1.将字符串转化为char数组,然后逆序输出

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();
        char[] chars = str.toCharArray();
        for(int i = (chars.length-1);i>=0;i--){
            System.out.print(chars[i]);
        }
    }
}

2.在读取的时候,就将字符串的字符挨个存储到char[]数组中

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        InputStream is = System.in;
        int available = is.available() - 1;
        char[] arr = new char[available];
        while (available-- > 0) {
            arr[available] = (char)is.read();
        }
//         for (char c : arr) {
//             System.out.print(c);
//         }                        //可以遍历输出数组
        String result = String.valueOf(arr);//也可以直接用String.valueOf()方法
                                            //将char数组转化为字符串
        System.out.println(result);
    }
}

 3.将字符串转为StringBuffer类(或者StringBuilder类),然后直接用.reverse()方法倒序输出

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

难度加强:句子的倒序输出

1.将句子用.split(” “) 分割,将各单词按照顺序存到String数组中,然后逆序输出String数组

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line=br.readLine();
        String[] str=br.readLine().split("[^A-Za-z]");//以所有非字母符号作为分割
        for(int i=(str.length-1);i>0;i--){
            System.out.print(str[i]+" ");
        }
        System.out.print(str[0]);

    }
}

    原文作者:c_atnip_
    原文地址: https://blog.csdn.net/c_atnip_/article/details/125943420
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞