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;
}
相关推荐
草莓熊Lotso17 小时前
Linux 实战:从零实现动态进度条(含缓冲区原理与多版本优化)
linux·运维·服务器·c++·人工智能·centos·进度条
行稳方能走远18 小时前
Android C++ 学习笔记3
android·c++
练习时长一年18 小时前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
FL162386312921 小时前
[C#][winform]基于yolov8的水表读数检测与识别系统C#源码+onnx模型+评估指标曲线+精美GUI界面
开发语言·yolo·c#
小白菜又菜1 天前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
cnxy1881 天前
围棋对弈Python程序开发完整指南:步骤1 - 棋盘基础框架搭建
开发语言·python
wuhen_n1 天前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo1 天前
leetcode 2483
数据结构·算法·leetcode
程序员-周李斌1 天前
Java 死锁
java·开发语言·后端
Xの哲學1 天前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算