[英]Am I missing something in my function?
This is what I have so far and I keep getting an error. 这就是我到目前为止所得到的错误。 Any help? 有帮助吗?
void ReverseString(char* string) {
int len = strlen(string);
for(int i = 0; i < len; i++)
{
string[i] = string[len-i];
}
}
i
is 0
you'll be accessing string[len]
which is incorrect as the valid index in an array of length len
are [0,len-1]
当i
为0
您将访问string[len]
,这是不正确的,因为长度为len
的数组中的有效索引为[0,len-1]
If I understand you intent correctly you are trying to reverse the string but I can see a few things missing: 如果我理解你的意图正确你试图扭转字符串但我可以看到一些缺失的东西:
The following snippet fixes these issues: 以下代码段修复了这些问题:
int len = strlen(string);
for(int i = 0; i < len/2; i++) {
swap(string[len-i-1],string[i]);
}
First of all, you would get an error on line 6. 首先,你会在第6行得到一个错误。
Change the {
into }
. 改变{
into }
。 Then try again. 然后再试一次。
Besides two already mentioned errors: 除了两个已经提到的错误:
You'll make a palindrom out of the original string. 你会用原始字符串制作一个回文。 The first half will became equal to second half inversed. 上半场将与下半场相反。 However, the second half will remain the same. 但是,下半场将保持不变。 This is not what the function name declares. 这不是函数名称声明的内容。
This is tagged C++, do it the C++ way... 这是标记的C ++,用C ++方式做...
std::string ReverseString(std::string str)
{
std::reverse(str.begin(), str.end());
return str;
}
should be string[i] = string[len-i-1];
应该是string[i] = string[len-i-1];
// added (untested):
void ReverseString(char * string) {
int len = strlen(string);
for(int i = 0; i < len / 2; i++)
{
string[i] ^= string[len-i-1];
string[len-i-1] ^= string[i];
string[i] ^= string[len-i-1];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.