C++使用指针反转字符串

标签 c++ string pointers

我的任务是接收用户输入的字符串并反转字符串的顺序并打印出结果。我的代码是这样的:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main() {
    string input;
    char *head = new char, *tail = new char;
    char temp;
    //Get the string from the user that will be reversed
    cout << "Enter in a string that you want reversed: ";
    getline(cin, input);
    //Create and copy the string into a character array
    char arr[input.length()];
    strcpy(arr, input.c_str());
    //Set the points of head/tail to the front/back of array, respectably
    head = &arr[0]; tail = &arr[input.length()-1];
    //Actual reversal part of the code (Does not work)
    for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }
    //Print the character array
    for(int i=0; i<input.length(); i++) {
        cout << arr[i];
    }
    //Free up memory
    delete head; delete tail;
    head = NULL; tail = NULL;
    return 0;
}

当我打印它时,几乎没有任何改变,而且我似乎不明白为什么,因为我是指针的新手。这是我遇到问题的特定 block :

    for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }

非常感谢任何有关如何解决此问题的输入或一般的指针知识。

最佳答案

你的方法很好但是......

for(int i=0; i<input.length(); i++) {
        temp = *(tail);
        *tail = *head;
        *head = temp;
        tail --; head ++;
    }

您没有尝试在纸上解决这个问题吗?您将每对字母交换两次,使数组恢复到原来的顺序。

只需更改迭代的限制,当 headtail 在中间相遇时停止,就可以了:

for(int i=0; i<input.length()/2; i++) {
  ...
}

关于C++使用指针反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472933/

相关文章:

c++ - OpenGL,将透明纹理与对象颜色混合

c - 字符串长度错误

java - 我应该预初始化一个在多个分支中被覆盖的变量吗?

pointers - 如何在go中定义一个指针,然后将这个指针传递给一个func来改变它的值?

c++ - 快速获取 "improve"单位长度 vector 的长度

c++ - 3D数组中的偏移量计算

arrays - SWIFT:大量字符串的快速累积

c - 指针相关查询

c - 在 C 中取消引用

c++ - 其构造函数抛出异常的对象的异常处理是否可以接近其基于代码的堆栈创建?