要倒序输出字符串,可以使用循环从字符串的最后一个字符开始逐个输出字符。
下面是一个示例代码:
#include#include using namespace std; int main() { string str = "Hello World!"; int length = str.length(); for (int i = length - 1; i >= 0; i--) { cout << str[i]; } return 0; }
输出结果为:
!dlroW olleH
首先使用str.length()
获取字符串的长度,然后从最后一个字符开始循环到第一个字符。在循环中,使用str[i]
访问字符串的每个字符,并使用cout
输出。