簡體   English   中英

這兩個給出的例子有什么區別

[英]What's the difference between these two given examples

我是 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"*/

代碼的 rest 將是這樣的

if(c == 0){
    cout<<"It is a Palindrome";
}
//if the value of C is !=0
else{
    cout<<"It is not a Palindrome";
}

}

這是為什么? 提前感謝那些會回答的人。 :)

除了首先使用一個額外的變量len之外,這兩個示例都是相同的。

這段代碼實際上是在反轉字符串。 如果str1包含"123"那么str2將包含"321"

Function strlen(str1)返回str1的長度,但在 Arrays 的 C++ 索引中從0開始,這就是為什么最后一個元素索引將比長度小strlen(str1) - 1的原因。

更新

即使有更新的信息,第一個問題的答案仍然相同,這兩個示例本質上是相同的。 由於下面解釋的原因,結果的差異是同時發生的。

char str1[20],str2[20];

此代碼創建兩個 20 char數組但未初始化。 這意味着初始值可以是隨機的。

現在當你調用cin.getline(str1, 20); 它不僅會寫入您輸入的字符串,還會在其末尾添加一個終止字符'\0' 我們的反轉邏輯只反轉字符串,但不會在str2的末尾插入終止符'\0' ,這意味着str2str1長得多(直到找到'\0' )。 因此,他們永遠不會正確比較。

解決此問題的一個簡單方法是在使用 arrays 之前對其進行零填充,在 C++ 中,有一種簡單的方法可以做到這一點:

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

如果要將 arrays 用作字符串,將 arrays 填零始終是一個好習慣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM