> For the complete documentation index, see [llms.txt](https://zedive.gitbook.io/project-l/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zedive.gitbook.io/project-l/part-1/basic_data_structure/array_and_string/string-buffer/reverse-words-in-a-string.md).

# Reverse Words in a String

## Question ([LC.151](https://leetcode.com/problems/reverse-words-in-a-string/))

## Analysis

StringBuffer example. Where you have to append a lot of times.

## Code

```java
/**
 * Store each work in map then reverse the whole map
 */
public String reverseWords(String s) {
    String[] words = s.trim().split("[ ]+");

    StringBuilder result = new StringBuilder();
    if (words.length > 0) {
        for (int i = words.length - 1; i > 0; i--) {
            result.append(words[i]);
            result.append(" ");
        }
        result.append(words[0]);
    }

    return result.toString();
}
```
