> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/strings/string-reverse.md).

# 字符串逆序

### 方法一：像字符数组一样倒序输出

```cpp
string s;
cin >> s;
for (int i = s.size() - 1; i >= 0; i--)
    cout << s[i];
```

### 方法二：使用 reverse

```cpp
#include <algorithm>
string s = "hello";
reverse(s.begin(), s.end());
cout << s;        // olleh
```

### 方法三：递归（原来是错的）

原笔记用 `!` 作为结束标志，只对特定输入成立，应改为按长度判断：

```cpp
void printReverse(string &s, int i) {
    if (i >= (int)s.size()) return;   // 正确的终止条件
    printReverse(s, i + 1);
    cout << s[i];
}
```

### 字符数组版

```cpp
char s[100];
cin >> s;
for (int i = strlen(s) - 1; i >= 0; i--)
    cout << s[i];
```

### 要点

* 终止条件要基于真实长度，不要依赖某个特殊字符。
* 日常优先用 `reverse`，简洁且不易出错。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/strings/string-reverse.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
