溫馨提示×

c++怎么倒序輸出字符串

c++
小億
459
2023-12-04 10:57:44
欄目: 編程語言

要倒序輸出字符串,可以使用循環(huán)從字符串的最后一個字符開始逐個輸出字符。

下面是一個示例代碼:

#include <iostream>
#include <string>
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()獲取字符串的長度,然后從最后一個字符開始循環(huán)到第一個字符。在循環(huán)中,使用str[i]訪問字符串的每個字符,并使用cout輸出。

0