gpt4 book ai didi

c++ - 在 C++ 中用指针和函数反转字符串

转载 作者:行者123 更新时间:2023-11-27 22:33:02 25 4
gpt4 key购买 nike

我正在尝试创建一个程序,用 C++ 中的指针和函数反转字符串,但到目前为止,我的方法只返回一个空字符串,而不是反转的字符串。

#include <iostream>

using namespace std;

void invertS(string *str_ptr );

int main()
{
string value {"Hello"};
string *str_ptr {nullptr};
str_ptr = &value;
invertS(str_ptr);
cout << value;
};

void invertS(string *str_ptr) {
string str = *str_ptr;
string temp = "";
int length = str.length();
int j = length - 1;
for (int i = 0; i < length; i++) {
temp[i] = str[j];
j--;
};
*str_ptr = temp;
};

结果始终只是一个空字符串。请注意,我将 str_ptr 引用的字符串分配给函数内的一个新字符串,以便我可以在该字符串上使用 .length。据我所知,因为 .length 不能用在指针上。如果有更好的方法来做到这一点,我也很高兴知道它是如何进行的。

最佳答案

问题是您正在初始化长度为零的临时字符串,然后尝试访问索引(IMO 应该会失败)。简单的解决方法是创建原始字符串的拷贝,以便长度与要反转的原始字符串相同。

// Example program
#include <iostream>

using namespace std;

void invertS(string *str_ptr );

int main()
{
string value {"Hello"};
string *str_ptr {nullptr};
str_ptr = &value;
invertS(str_ptr);
cout << "Reversed string: " << value << endl;
};

void invertS(string *str_ptr) {
string str = *str_ptr;
string temp {str};
int length = str.length();

int j = length - 1;
for (int i = 0; i < length; i++) {
temp[i] = str[j];
j--;
};
*str_ptr = temp;
};

关于c++ - 在 C++ 中用指针和函数反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58535614/

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