使用StringBuilder反转一个句子

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

Reverse a sentence using StringBuilder

问题

public String reverseWords(String s) {
    int i = s.length() - 1;
    StringBuilder resultBuilder = new StringBuilder();
    
    while (i >= 0) {
        while (i >= 0 && s.charAt(i) == ' ') {
            i--;
        }
        if (i < 0) {
            break;
        }
        
        int j = i;
        while (j >= 0 && s.charAt(j) != ' ') {
            j--;
        }
        
        String word = s.substring(j + 1, i + 1);
        resultBuilder.append(word).append(' ');
        
        i = j;
    }
    
    return resultBuilder.toString().trim();
}
英文:

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.

public String reverseWords(String s) {
    
    int i = 0;
    int j = 0;
    String result = &quot;&quot;;
    while(s.length()&gt;i){
        
        while(s.length()&gt;i &amp;&amp; s.charAt(i)==&#39; &#39;){
            i++;
        }
        if(i&gt;=s.length()) break;   
        
        j = i;
        while(s.length()&gt;j &amp;&amp; s.charAt(j)!=&#39; &#39;){
            j++;
        }

        
        String word = s.substring(i,j);
        result = word+&quot; &quot;+result;
      
        
        i = j;
    }
    return result.trim();
}

答案1

得分: 0

你可以按以下方式使用StringBuilder

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

输出结果:

eulb si yks eht
英文:

You can use StringBuilder as follows:

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

Output:

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:

确定