使用StringBuilder反转一个句子

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

Reverse a sentence using StringBuilder

问题

  1. public String reverseWords(String s) {
  2. int i = s.length() - 1;
  3. StringBuilder resultBuilder = new StringBuilder();
  4. while (i >= 0) {
  5. while (i >= 0 && s.charAt(i) == ' ') {
  6. i--;
  7. }
  8. if (i < 0) {
  9. break;
  10. }
  11. int j = i;
  12. while (j >= 0 && s.charAt(j) != ' ') {
  13. j--;
  14. }
  15. String word = s.substring(j + 1, i + 1);
  16. resultBuilder.append(word).append(' ');
  17. i = j;
  18. }
  19. return resultBuilder.toString().trim();
  20. }
英文:

The below code I used string as result and just reverse sentence for example input: " the sky is blue " and I get output:"blue is sky the". How I can use SpringBuilder instead String and then how I can reverse sentence and also words? example input: " the sky is blue " and I want this output "eulb is yks eht"
Please help me to modify the below code.

  1. public String reverseWords(String s) {
  2. int i = 0;
  3. int j = 0;
  4. String result = &quot;&quot;;
  5. while(s.length()&gt;i){
  6. while(s.length()&gt;i &amp;&amp; s.charAt(i)==&#39; &#39;){
  7. i++;
  8. }
  9. if(i&gt;=s.length()) break;
  10. j = i;
  11. while(s.length()&gt;j &amp;&amp; s.charAt(j)!=&#39; &#39;){
  12. j++;
  13. }
  14. String word = s.substring(i,j);
  15. result = word+&quot; &quot;+result;
  16. i = j;
  17. }
  18. return result.trim();
  19. }

答案1

得分: 0

你可以按以下方式使用StringBuilder

  1. String str = " the sky is blue ";
  2. str = str.replaceAll("\\s+", " ");
  3. StringBuilder sb = new StringBuilder(str.trim());
  4. System.out.println(sb.reverse().toString());

输出结果:

  1. eulb si yks eht
英文:

You can use StringBuilder as follows:

  1. String str = &quot; the sky is blue &quot;;
  2. str = str.replaceAll(&quot;\\s+&quot;, &quot; &quot;);
  3. StringBuilder sb = new StringBuilder(str.trim());
  4. System.out.println(sb.reverse().toString());

Output:

  1. eulb si yks eht

huangapple
  • 本文由 发表于 2020年9月3日 15:56:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63719224.html
匿名

发表评论

匿名网友

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

确定