比较字符串的总值?

时间:2013-10-10 18:39:55

标签: c string

说我有两个字符串,如

输入1:“xyz789”
输入2“mno123”

有没有办法比较它们的值,然后输出S1是大于,等于还是小于S2?

我只用标准的lib手工完成这个,到目前为止只能检查它们的长度(这是一个安全的假设,即较长的字符串较大,但在比较相似的长度时会变得更难。

int compare_string(char *s1, char *s2)
{
   while(*s1==*s2)
   {
      if ( *s1 == '\0' || *s2 == '\0' )
         break;

      s1++;
      s2++;
   }
   if( *s1 == '\0' && *s2 == '\0' )
      return 0;
   else
      return -1;
}

1 个答案:

答案 0 :(得分:3)

The function you are looking for is named strcmp(). This function is defined to return three possible values, depending on whether the first string is greater than, equal to, or less than the second string. For the sake of completeness, this entire paragraph is a link to the man page for the strcmp() function. Please make sure to read it.

严格来说,说该函数返回三个可能的值并不完全正确。如果字符串不同,该函数返回负值或正值,但对返回的负值或正值没有限制。换句话说,我们无法保证只返回-101