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 小时前
构造函数抛出异常:C++对象部分初始化的陷阱与应对策略
c++
有意义2 小时前
深度拆解分割等和子集:一维DP数组与倒序遍历的本质
前端·算法·面试
xlp666hub3 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
用户726876103373 小时前
解放双手的健身助手:基于 Rokid AR 眼镜的运动计时应用
算法
Wect4 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·typescript
不想写代码的星星4 小时前
static 关键字:从 C 到 C++,一篇文章彻底搞懂它的“七十二变”
c++
xlp666hub20 小时前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
程序员小崔日记1 天前
大三备战考研 + 找实习:我整理了 20 道必会的时间复杂度题(建议收藏)
算法·408·计算机考研
lizhongxuan1 天前
AI小镇 - 涌现
算法·架构