【发布时间】:2021-05-22 03:52:59
【问题描述】:
我是 C++ 的初学者,实际上是自己编程。我只想问,这两个例子有什么区别。 “len = strlen(str1)-1”和“i = strlen(str1)-1”有什么区别
代码的顶部将是这样的:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str1[20],str2[20];
int c, i ,j, len;
cout<<"Enter a word: ";
cin.getline(str1, 20);
示例 1:
//reverse
for (i = strlen(str1)-1, j = 0; i >= 0; i--, j++){
str2[j] = str1[i];
}
//compare string
c = strcmp(str1, str2);
/*This does not work because the value of 'c' will be -1 if the input
is "lol" which is palindrome*/
和示例 2:
//reverse
len = strlen(str1)-1;
for (i = len, j = 0; i >= 0; i--, j++){
str2[j] = str1[i];
}
//compare string
c = strcmp(str1, str2);
/*This does work in other hand, because of the variable "len"*/
其余的代码将是这样的
if(c == 0){
cout<<"It is a Palindrome";
}
//if the value of C is !=0
else{
cout<<"It is not a Palindrome";
}
}
这是为什么呢?提前感谢那些会回答的人。 :)
【问题讨论】:
-
"如果 strs 是回文,则返回 0" - 什么?是吗?
-
-1 是因为 C++ 容器索引从
0开始,而不是1。所以n-element 容器中的最后一个元素具有索引n-1而不是索引n。 -
这是无法回答的。您的 cmets 提到了代码中不存在的返回值。您也没有包括所用变量的类型,也没有包括两个字符串的初始化方式。请修改您的问题。
-
嗨,Sander De Dycker,我已经编辑了我的问题,希望这能澄清它。 :)
-
@Programming_Student 我已经更新了答案。虽然代码有很多需要改进的地方,但这应该足够好开始了。
标签: c++ structure declaration variable-declaration string.h