【问题标题】:What's the difference between these two given examples这两个给出的例子有什么区别
【发布时间】: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


【解决方案1】:

两个例子都是一样的,只是首先使用了一个额外的变量len

这段代码实际上是在反转字符串。如果str1 包含"123",那么str2 将包含"321"

函数 strlen(str1) 返回 str1 的长度,但在 C++ 中,数组的索引从 0 开始,这就是为什么最后一个元素索引将比长度小一,因此是 strlen(str1) - 1

更新

即使有更新的信息,第一个问题的答案仍然是相同的,这两个示例在本质上是相同的。由于下面解释的原因,结果的差异是一种巧合。

char str1[20],str2[20];

此代码创建两个数组,包含 20 个 char,但未初始化。这意味着初始值可以是随机的。

现在,当您调用cin.getline(str1, 20); 时,它不仅会写入您输入的字符串,还会在其末尾添加一个终止符'\0'。我们的反转逻辑只反转字符串,但不会在str2 的末尾插入终止'\0',这意味着str2str1 长得多(直到找到'\0')。因此,它们永远不会正确比较。

解决这个问题的一个简单方法是在使用数组之前将它们填零,而在 C++ 中有一种简单的方法可以做到这一点:

char str1[20] = { 0 }, str2[20] = { 0 };

如果您打算将 then 用作字符串,那么将数组填零始终是一个好习惯。

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2018-01-13
    • 2012-06-12
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多