c++字符串怎么逆序输出

c++
1586
2024/5/14 11:39:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

有多种方法可以逆序输出一个C++字符串。以下是其中一种方法:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello World";
    
    // 逆序输出字符串
    for (int i = str.length() - 1; i >= 0; i--) {
        std::cout << str[i];
    }
    
    return 0;
}

在上面的代码中,我们首先定义了一个字符串str,然后使用一个for循环逆序输出字符串中的每个字符。输出结果将是dlroW olleH

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: C++数组引用对性能的影响