我在JAVA遇到麻烦。我试图让字符串向后打印每个单词。
示例:Hello World将是" olleh dlrow"
以下是我的课程。谢谢您的帮助。
public class ReadReverse {
String message = "Hello nice to meet you in CS102";
String[] myStrings = message.split(" "); //Makes an array of the words split up by spaces
String result = "";
{
// gets the length of the array and splits it up by each word
for (int i = 0; i < myStrings[i].length(); i++) {
message.push(myStrings[i].at(i));
// sets th length to the length of the word
int length = message.length();
// pops the letter out into the new stack
for (i = 0; i < length; i++) {
result += myStrings;
}
// checks to see if it is at the end of the string.
if (i != message.length() - 1) {
result += " ";
}
}
}
}
答案 0 :(得分:2)
您可以通过多种方式实现字符串反转。
看看这个:
class ReverseString
{
public static void main(String[] args)
{
String input = "Hello world";
String[] words = input.split(" ");
String reversedString = "";
for (int i = 0; i < words.length; i++)
{
String word = words[i];
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
reversedString = reversedString + reverseWord + " ";
}
System.out.println(input);
System.out.println(reversedString);
}
}
答案 1 :(得分:1)
我会以这种方式逐字回复:
String input = "Hello world";
String[] words = input.split(" ");
StringBuilder reversed = new StringBuilder(
for (String word : words) {
reversed.append(new StringBuilder(word).reverse())
.append(" ");
}
System.out.println(reversed);
或者以这种方式使用java 8流:
String input = "Hello world";
StringBuilder reversed = new StringBuilder();
Stream.of(input.split(" "))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.forEach(word -> reversed.append(word).append(" "));
System.out.println(reversed);
输出:olleH dlrow