反向字符串打印方法 [英] Reverse string printing method
问题描述
我正在尝试解决以下问题,但是如何编写将String用作参数的方法呢?
I am trying to solve the following problem but how do write the method that accepts String as an argument?
编写一个名为
printReverse
的方法,该方法接受String
作为参数并以相反的顺序打印字符.如果为空字符串作为参数传递,该方法不应产生任何输出.确保编写一个 main 方法,该方法可以令人信服地演示您的程序在行动.请勿使用相反的方法StringBuilder
或StringBuffer
类!
Write a method named
printReverse
that accepts aString
as an argument and prints the characters in the opposite order. If the empty string is passed as an argument, the method should produce no output. Be sure to write a main method that convincingly demonstrates your program in action. Do not use the reverse method of theStringBuilder
orStringBuffer
class!
到目前为止,我已经以一种更简单的方式解决了该问题:
So far I have solved it in a easier manner:
import java.util.Scanner;
class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: " + reverse);
}
}
推荐答案
我强烈建议您阅读您可以轻松地做到:
private static String myReverse(String str) {
String reverse = "";
int length = str.length();
for( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + str.charAt(i);
}
return reverse;
}
在您的 main
中,您只需:
String reversed = myReverse(in.nextLine());
Note that the method is static
because you're referring to it from a static manner (main
method). If you don't want it to be static, you'll have to access it via an object.
还请注意,对于 for
循环,始终使用大括号是一个好习惯,即使它只包含一行.
Also note that it's a good practice to always have curly brackets for for
loops, even if it contains a single line.
这篇关于反向字符串打印方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!