gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:21:03 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com