[英]Reversing string by word in java (not using StringBuilder)
I'm having trouble getting a method to return anything.我在获取返回任何内容的方法时遇到问题。 The code is supposed to take a string, reverse the string by word, and return the new string.
该代码应该接受一个字符串,逐字反转字符串,然后返回新字符串。
This is for a school assignment, and i'm trying to avoid using stringbuilder since it's not covered by the text.这是一个学校作业,我试图避免使用 stringbuilder,因为它没有包含在文本中。 I'm also trying to use syntax I understand as much as possible for obvious reasons.
出于显而易见的原因,我也在尝试尽可能多地使用我理解的语法。
public static String reverseByWord(String s){
String forward[] = s.split("\\s+");
String backward = new String();
for (int i=forward.length-1; i< forward.length-1; i--){
backward += forward[i];
}
return backward;
Input example: "The quick brown fox" Output expected: "fox brown quick The" Output: nothing输入示例:“The quick brown fox” 预期输出:“fox brown quick The” 输出:没有
for (int i=forward.length-1; i< forward.length-1; i--){
backward += forward[i];
}
This line, int i = forward.length-1; i < forward.length-1
这一行,
int i = forward.length-1; i < forward.length-1
int i = forward.length-1; i < forward.length-1
You set i to forward.length - 1
, then you immediately tell the for loop that it should executed only if i is less than forward.length - 1
您将 i 设置为
forward.length - 1
,然后您立即告诉 for 循环它仅在 i 小于forward.length - 1
时才应执行
A really simple solution, just set the condition to i >= 0
一个非常简单的解决方案,只需将条件设置为
i >= 0
Your for loop condition is not correct.您的for 循环条件不正确。 Your logic should be from last String length to starting of string ie 0.
您的逻辑应该是从最后一个字符串长度到字符串开头,即 0。
for (int i=forward.length-1; i >= 0; i--){
backward += forward[i];
}
Simple code snippet for your solution : 您的解决方案的简单代码段:
//pattern to be looked for
Pattern pattern = Pattern.compile("\\s");
// splitting String with a pattern
String[] temp = pattern.split(str);
String result = "";
// the string in reverse order.
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
For Working Example - Click Here . 对于工作示例- 单击此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.