简体   繁体   English

比较手动输入的字符串和用户输入的字符串

[英]compare manually entered string with user entered

I try to read user input until user enters "End of story". 我尝试读取用户输入,直到用户输入“故事结束”为止。 I can successfully compare 2 user entered words via following code but I could not managed to compare user entered string with my string (in this case "test"). 我可以通过以下代码成功比较2个用户输入的单词,但无法将用户输入的字符串与我的字符串进行比较(在这种情况下为“测试”)。 It keeps returning 0. 它一直返回0。

How should I compare them ? 我应该如何比较它们?

I can't use string.h I'm preparing for an exam and string.h is forbidden to use. 我不能使用string.h我正在准备考试,并且string.h被禁止使用。

int getLength(char str[]) {
  int i;
  for (i = 0; str[i] != '\0'; i++)
    ;
  return i - 1;
}

int strcompare(char alpha[], char bravo[]) {
  if (getLength(alpha) == getLength(bravo)) {

    int i;
    for (i = 0; i <= getLength(alpha); i++) {
      if (alpha[i] != bravo[i]) {
        return 0;
      }
    }
    return 1;    // theyre same
  } else {
    //different lengths cant be same
    return 0;    // not same
  }
  return -1;
}


char c[500], h[500] = { 't', 'e', 's', 't', '\0' };
gets(c);
printf("%d",strcompare(c,h));

The code you wrote has one extraneous part and a part which can't be reached, as well as suboptimal issues mentioned in the comments. 您编写的代码有一个无关紧要的部分,一个无法实现的部分,以及注释中提到的次优问题。 The unreachable return -1 statement was probably intended to return -1 if sizes don't match. 如果大小不匹配,则无法到达的return -1语句可能打算返回-1

#include <stdio.h>

int getLength(char str[])
{
  int i;
  for( i = 0 ; str[i] != '\0' ; i++ );
return i;
}

int strcompare(char alpha[], char bravo[]){
  int a = getLength(alpha);
  int b = getLength(bravo);
  if(a == b){
     int i;
     for( i = 0 ; i <= a ; i++ ){
         if(alpha[i] != bravo[i])
             return 0;   // sizes match, contents don't  
         }
   return 1;             // they're same
   }
return -1;               // sizes don't match
}


int main(void){        
  char c[500], h[500] = {'t','e','s','t','\0'};
  gets(c);
  printf("%d\n",strcompare(c,h));
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM