我正在尝试做一个简单的反向任务,例如:将字符串“ you are you”更改为“ you are how”。
这是我的代码:
public class Program {
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String [] retString = new String[givenString.length];
int last = givenString.length - 1;
for (int i = 0; i < givenString.length; i++) {
retString [i] = givenString[last--];
}
return retString.toString();
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
我得到一个奇怪的输出:
[Ljava.lang.String;@e76cbf7
最佳答案
这是一个解决方案:
public class Program {
public static String revSentence (String str) {
String retString = "";
String [] givenString = str.split(" ");
for (int i=givenString.length-1; i>=0; i--) {
retString += givenString[i] + " ";
}
return retString;
}
public static void main(String[] args) {
String m = "how are you";
System.out.print(revSentence(m));
}
}
对其进行了修改,以使“ revSentence”函数返回一个String,并对代码进行了一些改进。请享用!