如何逐字逆转字符串而不使用数组、split() 或 StringBuilder。

huangapple go评论107阅读模式
英文:

How can I reverse a string word by word without using arrays, split() or StringBuilder

问题

以下是您要翻译的内容:

我试图逐词反转字符串,但不使用数组,split()StringBuilder。到目前为止,这是我的代码。它可以工作,但输出不符合我的预期。请查看我附带的图片以获取输出结果。
我希望程序将每个单词输出到新行。同时请注意单词 "curtain" 中缺少字母 "n",并且最后两个单词之间没有空格。我该如何修复这个问题?

  1. public static void main(String[] args) {
  2. String sentence = new String("pay no attention to that man behind the curtain");
  3. String reversed = "";
  4. int endIndex = sentence.length() - 1;
  5. for (int i = endIndex; i >= 0; i--) {
  6. if (sentence.charAt(i) == ' ') {
  7. reversed += sentence.substring(i, endIndex);
  8. endIndex = i;
  9. }
  10. }
  11. reversed += sentence.substring(0, endIndex);
  12. System.out.println(reversed);
  13. }

![在此输入图片描述][1]

  1. [1]: https://i.stack.imgur.com/mpW2R.png
  2. <details>
  3. <summary>英文:</summary>
  4. I&#39;m trying to reverse a string word by word without using arrays, `split()` or `StringBuilder`. This is my code so far. It works, but my output is not how I want it. See my image for output.
  5. I want my program to output each word on a new line. Also notice how the letter &quot;n&quot; is missing from curtain and there is no space between the last two words. How can I fix this?
  6. public static void main(String[] args) {
  7. String sentence = new String(&quot;pay no attention to that man behind the curtain&quot;);
  8. String reversed = &quot;&quot;;
  9. int endIndex = sentence.length()-1;
  10. for(int i = endIndex; i &gt;= 0; i--) {
  11. if(sentence.charAt(i) == &#39; &#39;) {
  12. reversed += sentence.substring(i, endIndex);
  13. endIndex = i;
  14. }
  15. }
  16. reversed += sentence.substring(0, endIndex);
  17. System.out.println(reversed);
  18. }
  19. ![enter image description here][1]
  20. [1]: https://i.stack.imgur.com/mpW2R.png
  21. </details>
  22. # 答案1
  23. **得分**: 1
  24. ```java
  25. 尝试一下这段代码:
  26. import java.util.Scanner;
  27. public class ReverseString
  28. {
  29. public static void main(String[] args)
  30. {
  31. System.out.println("输入要反转的字符串:");
  32. Scanner read = new Scanner(System.in);
  33. String str = read.nextLine();
  34. String reverse = "";
  35. for(int i = str.length() - 1; i >= 0; i--)
  36. {
  37. reverse = reverse + str.charAt(i);
  38. }
  39. System.out.println("反转后的字符串是:");
  40. System.out.println(reverse);
  41. }
  42. }
英文:

Try this code out:

  1. import java.util.Scanner;
  2. public class ReverseString
  3. {
  4. public static void main(String[] args)
  5. {
  6. System.out.println(&quot;Enter string to reverse:&quot;);
  7. Scanner read = new Scanner(System.in);
  8. String str = read.nextLine();
  9. String reverse = &quot;&quot;;
  10. for(int i = str.length() - 1; i &gt;= 0; i--)
  11. {
  12. reverse = reverse + str.charAt(i);
  13. }
  14. System.out.println(&quot;Reversed string is:&quot;);
  15. System.out.println(reverse);
  16. }
  17. }

答案2

得分: 1

首先,有一种更好的方法来反转单词。但让我们看看你的程序。

我希望我的程序在每一行输出每个单词。

如果你想要在新的一行中打印每个单词,你可以将每个单词添加到一个单词列表中,并在新的一行中打印每个单词,或者你可以在每个单词的末尾添加 "\n"。

还要注意,“curtain” 中缺少字母 “n”,并且最后两个单词之间没有空格。

这是因为 endIndexsentence.length()-1 开始,而在 Java 中,substring 的工作方式是从 startIndex 到 endIndex - 1,即 endIndex 是独占的,startIndex 是包含的。你可以通过声明 endIndex = sentence.length() 并从 i = sentence.length()-1 迭代到 0 来修复它。

修复后的代码如下:

  1. public static void main(String[] args) {
  2. String sentence = new String("pay no attention to that man behind the curtain");
  3. String reversed = "";
  4. int endIndex = sentence.length();
  5. for(int i = sentence.length()-1; i >= 0; i--) {
  6. if(sentence.charAt(i) == ' ') {
  7. reversed += sentence.substring(i+1, endIndex) + "\n";
  8. endIndex = i;
  9. }
  10. }
  11. reversed += sentence.substring(0, endIndex);
  12. System.out.println(reversed);
  13. }

更好的方法是:

a) 将你的字符串转换为字符数组

b) 然后反转整个字符数组,变成:

niatruc eht dniheb nam taht ot noitnetta on yap

c) 然后在每个空格之间就地反转字母。

d) 这样你将得到表示以下内容的新字符数组:

curtain the behind man that to attention no pay

然后你可以从新的字符数组构造一个字符串。

英文:

First of all, there is a better way to reverse the words. But lets look at your program.

> I want my program to output each word on a new line.

If you want to print each word in a new line, you could either add each word to a list of words and print each word in a new line or you could just add "\n" at the end of each word.

> Also notice how the letter "n" is missing from curtain and there is no
> space between the last two words.

This is because the endIndex starts at sentence.length()-1 and substring in Java works by extracting from startIndex to endIndex - 1 i.e. endIndex is exclusive and startIndex is inclusive.
You can fix it by declaring endIndex = sentence.length() and iterate from i = sentence.length()-1 to 0.

With that the code would be:

  1. public static void main(String[] args) {
  2. String sentence = new String(&quot;pay no attention to that man behind the curtain&quot;);
  3. String reversed = &quot;&quot;;
  4. int endIndex = sentence.length();
  5. for(int i = sentence.length()-1; i &gt;= 0; i--) {
  6. if(sentence.charAt(i) == &#39; &#39;) {
  7. reversed += sentence.substring(i+1, endIndex) + &quot;\n&quot;;
  8. endIndex = i;
  9. }
  10. }
  11. reversed += sentence.substring(0, endIndex);
  12. System.out.println(reversed);
  13. }

The better way is :

a) Convert your string to character array

b) Then reverse the whole character array which would become :

  1. niatruc eht dniheb nam taht ot noitnetta on yap

c) Then reverse the letters between each space in-place.

d) You will get back the new character array that represents:

  1. curtain the behind man that to attention no pay

and you can construct a string from the new character array.

huangapple
  • 本文由 发表于 2020年9月12日 03:44:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63853404.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定