> For the complete documentation index, see [llms.txt](https://heunnajo.gitbook.io/algorithms-problem-solving-skills/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heunnajo.gitbook.io/algorithms-problem-solving-skills/data-structures/reverse-sentence-word-by-word.md).

# Reverse Sentence word by word

> I : 2\
> &#x20;  I am happy today\
> &#x20;  We want to win\
> O : I ma yppah yadot\
> &#x20;   eW tnaw ot niw

\=>공백 문자 또는 줄바꿈 문자가 나오면 스택이 빌 때까지 pop()을 해서 문자를 출력한다.

**실수한 부분 복기**

```java
while(n-- >0) {
			String s = br.readLine();
			for(char c:s.toCharArray()) {
				//System.out.printf("c : %c",c);
				//System.out.println();
				if(c == ' ') {
					while(!st.isEmpty()) {
						System.out.print(st.pop());
						
					}
					System.out.print(c);
				}
				else {
					st.push(c);
				}
			}
		}
```

for-each 문을 돌 때 입력 String의 모든 character를 돌면서 정상적으로 출력됐지만 마지막 단어가 정상 동작하지 않았다. 그 이유는 스택 pop() 조건으로 공백문제가 나올 때만 다루었기 때문에 스택에 마지막 단어의 character가 push되긴 하지만 공백문자가 없기 때문에 pop(), 출력하지 않고 종료됐다.

**해결 방법**

1. 입력 String을 받을 때 .readLine()으로 받고, 저장할 때 줄바꿈 문자('\n')도 함께 저장해준다.
2. pop() 연산 조건을 다음과 같이 수정한다.

```java
while(n-- >0) {
			String s = br.readLine()+"\n";
			for(char c:s.toCharArray()) {
				//System.out.printf("c : %c",c);
				//System.out.println();
				if(c == ' ' || c == '\n') {
					while(!st.isEmpty()) {
						bw.write(st.pop());
					}
					bw.write(c);
				}
				else {
					st.push(c);
				}
			}
		}
```
