I see a few problems all in your first method: 1. In your first method you are returning words, which is just an array split, that's why you are getting the original output, because that's what you are returning. After your split, you can instantiate a new String to hold the reversed words with a =+. After each call to the second reversedWord method, you can add to the string an empty space " ". However this will also add a space after the last word of the sentence, so to make it even better I suggest you check if you are working on the last word, if not you add the space, if so, then you don't. Your second method is fine. Here is the working code: ```java public class Solution { public static void main(String[] args) { System.out.println(reverseWords("My name is Pedro")); } public static String reverseWords(String s) { String[] words = s.split(" "); String ss = ""; for(String word : words){ ss += reverseWord(word); ss += " "; } return String.join(" ", ss); } public static String reverseWord(String s){ char[] letters = s.toCharArray(); s=""; for(int i=letters.length-1;i>=0;i--){ s=s + letters[i]; } return s; } } ``` I also suggest you rename your methods better to signify what they are really doing. My variably ss is also very badly named. Answer from Pedro Cabral on teamtreehouse.com
🌐
LeetCode
leetcode.com › problems › reverse-words-in-a-string
Reverse Words in a String - LeetCode
Can you solve this real interview question? Reverse Words in a String - Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-words-in-a-given-string
Reverse words in a string - GeeksforGeeks
Reverse the entire string, then iterate through it to extract words separated by dots. Reverse each word individually and update the original string until the end is reached.
Published   October 29, 2025
Discussions

reversing words in a string in c - Stack Overflow
I have homework assignment: to write a function that reverse a string, and then write a function that reverses words in a string, using the first function. So if the input is: "have a nice day", the More on stackoverflow.com
🌐 stackoverflow.com
Return the reversed words in a string, while preserving the word order
Razvan Cirstea is having issues with: Hello, I am stuck trying to solve the following exercise: Given a string, you need to reverse the order of characters in each w... More on teamtreehouse.com
🌐 teamtreehouse.com
2
November 24, 2017
How to reverse characters in words of a string, but keep word order?
Reverses words in sentence. OP wants to reverse characters in the word. 2025-01-30T19:38:53.99Z+00:00 ... If you want to reverse a string by word: Example: 'Welcome to JavaScript' to 'JavaScript to Welcome' More on stackoverflow.com
🌐 stackoverflow.com
Reverse words in a string
You can remove return & ; in last line. In Rust, last expression is automatically returned. In 1.56, you will be able to use intersperse to avoid temporary allocation: fn reverse_words(words: &str) -> String { words.split(' ').rev().intersperse(" ").collect() } More on reddit.com
🌐 r/rust
6
2
August 8, 2021
🌐
AlgoMonster
algo.monster › liteproblems › 151
151. Reverse Words in a String - In-Depth Explanation
In-depth solution and explanation for LeetCode 151. Reverse Words in a String in Python, Java, C++ and more. Intuitions, example walk through, and complexity analysis. Better than official and forum solutions.
🌐
CodeChef
codechef.com › practice › course › strings › STRINGS › problems › PALINDRCHECK
Reverse Words in a String Practice Problem in Strings
Test your knowledge with our Reverse Words in a String practice problem. Dive into the world of strings challenges at CodeChef.
🌐
Stack Overflow
stackoverflow.com › questions › 59204364 › reversing-words-in-a-string-in-c
reversing words in a string in c - Stack Overflow
Sign up to request clarification or add additional context in comments. ... I'm afraid there are quite a few things to note here. First things first, the reason you're getting your segfault is that you're changing your token from strtok before using it and therefore it ends up being NULL once you call strcat. That part of your code should look like this once you've fixed it: char *token = strtok(a, " "); reverse(token); strcpy(new, token); token=strtok(NULL," "); while(token != NULL) { reverse(token); strcat(new, token); token = strtok(NULL, " "); }
Find elsewhere
🌐
Reddit
reddit.com › r/rust › reverse words in a string
r/rust on Reddit: Reverse words in a string
August 8, 2021 -

I took on a very simple problem that consisted in reversing the words in a sentence. Here's what I came up with:

fn reverse_words(words: &str) -> String {
    let parts: Vec<&str> = words.split(' ').rev().collect();
    return parts.join(" ");
}

fn main() {
    let words = "one two three";
    let rev_words = reverse_words(words);
    println!("words:    {:?}", words);
    println!("reversed: {:?}", rev_words);
}

I'd be thankful if more experienced rustaceans would point out how far that is from idiomatic Rust and any other general flaws.

🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-javascript › lessons › reversing-words-in-a-string-in-javascript
Reversing Words in a String in JavaScript
Consider the input string "Hello neat javascript_lovers_123". ... Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignalStart learning today! ... Afterward, it forms a single string with these reversed words, producing "olleH taen 321_srevol_tpircsavaj".
🌐
Codepath
guides.codepath.org › compsci › Reverse-Words-in-a-String
Reverse Words in a String | CodePath Cliffnotes
class Solution: def reverseWords(self, s: str) -> str: # Tokenize the input string to create a separate array arr = [] temp = " for c in s: if c != " ": temp += c elif temp != ": arr.append(temp) temp = " if temp != ": arr.append(temp) # Return a joined string version of the reversed array l, r = 0, len(arr) - 1 while l<r: arr[l], arr[r] = arr[r], arr[l] l += 1 r -= 1 return " ".join(arr)
🌐
LeetCode
leetcode.com › problems › reverse-words-in-a-string-iii
Reverse Words in a String III - LeetCode
Can you solve this real interview question? Reverse Words in a String III - Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
🌐
Scaler
scaler.in › home › reverse words in a string
Reverse Words in a String - Scaler Blog
September 30, 2024 - One of the easiest ways to solve this problem is by splitting the string and then saving it in reverse order. Another way is to swap the words from the start and end to achieve the reversed string.
🌐
AlgoMap
algomap.io › question-bank › reverse-words-in-a-string
Reverse Words in a String
Extract all the words from the string, ignoring extra spaces. Reverse the order of these words. Join them back together with a single space. This approach avoids the complexity of handling spaces manually and leverages built-in string manipulation functions.
Top answer
1 of 3
2

Here is a change to the function that makes the minimum changes to fix the bugs in the original code. Specifically made two changes: 1) Replaced the last while loop with a simple assignment to str at the bottom of the while (modified from earlier post). The right answer has already been calculated and this assignment moves the string forward without another while loop that had issues with falling off the end. 2) Put an else around the temp++ since it should not be done when a word was found or you can go off the end.

void reversed_words(char *str)
{
      char word[100];
      char *temp;
      char *zet;
      temp=str;
      int k=0;
      while(*temp)  //processing complete string
      {
          if(isalnum(*temp))
          {
             while(isalnum(*temp))      //extracting word from string
             {
                word[k]=*temp;
                k++;
                temp++;
             }
             word[k]='\0';
             k=0;
             strrev(word);   // Reverses the string
             zet=word;       
             while (*zet)   // Copying the reversed word into original string
             {
                *str = *zet;
                zet++;
                str++;
             }
          }
          else
          {
             temp++;
          }
          str = temp;
    }
}
2 of 3
1

This might be a problem:

         zet = word;
         while (*zet)   // Copying the reversed word into original string
         {
            *str = *zet;
            zet++;
            str++;
         }
         while (!isalnum(*str)) // Skipping all non-alphanumeric character(s)
         {
            str++;
         }

When it is processing the last word, it comes out of that first while loop with str pointing to either non-alphabetic junk at the end of the input string, or the '\0' terminator at the end of the string. In either case, the terminator is not alphanumeric, so the second while loop will continue reading until it finds a byte that happens to be alphanumeric, which is probably in uninitialized memory.

You could also have problems in your strrev or main functions, but you didn't post them.

It's also probably a good idea to consider what will happen if you pass this function a string with a 'word' longer than 99 characters.

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Write a function to reverse words in a string
November 19, 2018 - I got below test as a part of my job interview and I know how to reverse a string but don’t know how to reverse every third word in a string. Test is Using ES5 or ES6, write a function ‘reverseStringWords’ that will reverse every **third** word in a string.
🌐
Codewars
codewars.com › kata › 57a55c8b72292d057b000594
Reversing Words in a String | Codewars
You need to write a function that reverses the words in a given string. Words are always separated by a single space. As the input may have trailing spaces, you will also need to ignore unneccesa...