C++ 实现字符串逆序

C++ 实现字符串逆序

思路:

  1. 输入一个字符串。
  2. 使用双指针法,交换字符串的首尾字符,逐步向中间移动。
  3. 输出逆序后的字符串。
cpp 复制代码
#include <iostream>
#include <string>

using namespace std;

void reverseString(string &str) {
    int left = 0;
    int right = str.length() - 1;
    
    while (left < right) {
        // 交换左右两侧的字符
        char temp = str[left];
        str[left] = str[right];
        str[right] = temp;
        
        // 移动指针
        left++;
        right--;
    }
}

int main() {
    string input;
    cout << "Enter a string: ";
    getline(cin, input); // 获取输入的字符串,包括空格

    reverseString(input);
    cout << "Reversed string: " << input << endl;

    return 0;
}
相关推荐
现任明教教主~1 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411361 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
千里码aicood2 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
码匠许师傅2 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
做cv的小昊2 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له3 小时前
World-In-World: World Models in a Closed-Loop World
算法
无名猿3 小时前
new/delete 与 malloc/free:为什么绝对不能混用
c++·内存管理·现代c++·踩坑记录
小小小小钰儿3 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全