Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

java - How can I get a char array in reverse order?

my assignment question is like that

Write a program which prints the letters in a char array in reverse order using

void printReverse(char letters[], int size);

For example, if the array contains {'c', 's', 'c', '2', '6', '1'} the output should be "162csc".

I tried, but I don't know what it means

void printReverse(char letters[], int size);

I did this but there's a problem with calling the method "printReverse" into the main method

import java.util.Arrays;
import java.util.Collections;
 
public class search {

    public static void main(String[] args) {          
 
        char[] letters = {'e', 'v', 'o', 'l', '4'};
        printReverse();

    }

    public void printReverse(char[] letters, int size) {
    
        for (int i = letters.length-1; i >= 0 ; i--) {
        System.out.print(letters[i]);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make use of StringBuilder#reverse() method like this:

String reverse = new StringBuilder(new String(letters)).reverse().toString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...