Line reversal. Every other word

So I have a for loop that reverses every other word in a string. I can't figure out what condition is causing this.

for (int i = 0; i < words.length; i++) 
{
    stringBuilder.append(words[(words.length-1)-i]);
    stringBuilder.reverse()
}
newMessage = stringBuilder.toString();
return Message

      

+3


source to share


4 answers


stringBuilder.reverse()

reverse the whole line you are currently building on each iteration.

Try:

for (int i = 0 ; i < words.length ; i++) {
    String word = words[(words.length-1)-i];
    String reverse = new StringBuilder(word).reverse().toString();
    stringBuilder.append(reverse).append(" ");
}

      

Or even simpler, reversing at the end:



for (int i = 0 ; i < words.length ; i++) {
    stringBuilder.append(words[(words.length-1)-i]).append(" ");
}
newMessage = stringBuilder.reverse().toString();

      

Edit based on comments:

for (String w : words) {
    String reverse = new StringBuilder(w).reverse().toString();
    stringBuilder.append(reverse).append(" ");
}
newMessage = stringBuilder.toString();

      

+2


source


stringBuilder.reverse (); reverses the entire comment word, that line and your code won't undo your new post



0


source


First of all, your loop is more complex than it needs to be. If you want to reverse the words starting at the end, you just need to use the loop index for that, you don't need a calculation (words.length-1)-i

.

Another thing is when you call reverse()

on StringBuilder

, you change the whole line, not just the added part. What you can do is use temp StringBuilder

to do the reversal variable and the temp variable String

to separate undo from append.

Something like that:

StringBuilder reversedBuilder = new StringBuilder();
for (int i = words.length - 1; i >= 0; i --) 
{
    String reversed = reversedBuilder.append(words[i]).reverse().toString(); // reverse the word
    stringBuilder.append(reversed).append(" ");
    reversedBuilder.setLength(0); // clear the reversed
}

      

If you want, you can do it in one line of code (added with comments for clarification):

for (int i = words.length - 1; i >= 0; i --) 
{
    stringBuilder.append(new StringBuilder()  // create a temp string builder
                            .append(words[i]) // add the current word to temp string builder
                            .reverse()        // reverse the current word in the temp string builder
                            .toString())      // add the reversed word to stringBuilder
                 .append(" ");                // add the space to stringBuilder
}

      

0


source


var string = "hello world";

function reverseWords(string) {
   var words = string.split(' '),
   finals = [];

   words.forEach(function(word) {
     finals.push(word.split('').reverse().join(''););
   });

   return finals.join(' ');
 }

 reverseWords(string); // "olleh dlrow"

      

0


source







All Articles