C Primer Plus学习 三十 string.h strcmp()函数和strncmp ()变种

来源:互联网 发布:papi酱变声软件 编辑:程序博客网 时间:2024/06/08 02:27

       strcmp()函数把用户的响应和一个已有的字符串逬行比较

/* compare.c --这个程序可以满足要求*/
#include<stdio.h>
#include<string.h>
#define ANSWER "Grant"
#define MAX 40
int main(void)
{
char try[MAX];


puts("Who is buried in Greint tomb?");
gets(try);
while(strcmp(try,ANSWER)!=0)
{
puts("no that's wrong .try again.");
gets(try);

}
puts("That's right!");
/* compback.c -- strcmp ()的返回值 */
printf("strcmp(\"A\”,\”A\”)is "); 
printf("%d\n",strcmp("A","A"));

printf ( "strcmp(\" A\" ,\" B\") is ");
    printf( "%d\n",strcmp( "A","B"));
    
printf("strcmp(\”B\”,\”A\”)is");
printf("%d\n",strcmp("B","A"));

printf ( "strcmp(\” C\”,\” A\”) is " );
printf("%d\n",strcmp("C","A"));

printf( "strcmp(\" Z\" , \" a\" ) is ");
printf("%d\n" , strcmp( "z","a"));
 
printf ( "strcmp(\"apples\”,\"apple\”)is");
    printf("%d\n",strcmp("appies" ,"apple"));
return 0;
}

下面是一个系统上的输出结果:
strcmp( “A”,“A”)is 0 

strcmp( “A” , “B” ) is -1 

strcmp( "B”,“A”)is 1 

strcmp( “C” , “A” ) is 1 

strcmp( “Z” , “a” ) is -1 

strcmp< “apples” , “apple” ) is 1

由于任何非零值都为真,大多熟练的C程序员会把while语句简单地写为:

while (strcmp (try,ANSWER))。

我们不能把字符串比较写成这样:

while (try != ANSWER)

        ANSWER和try实际上是指针,因此比较式try!=ANSWER 并不检査这两个字符串是否一样,而是检查这两个字符串的地址是否一样。由于ANSWER和try被存放在不 同的位置,所以这两个地址永远不会一样,用户永远被告知他或她是“wrong”。

       我们需要的是一个可以比较字符串内容(content)而不是字符串地址(address)的函数。您可以自行 设计一个,但并不需要这样做,因为strcmp() (代表对ring comparison)函数就可以实现这个功能。这个函数对字符串的操作就像关系运算符对数字的操作一样。特别地,如果两个字符串参数相同,它就返回0。

       strcmp ()函数的一个优点是它比较的是字符串,而不是数组。尽管数组try占用40个内存单元,而 字串"Grant"只占用6个内存单元(一个用来存放空字符),但是函数在比较时只看try的第一个空字符之 前的部分。因此,strcmp ()可以用来比较存放在不同大小数组里的字符串。

       比较"A"和它本身,返回值是0。比较”A"和"B"的返回值是-1;两者交换,再进行比较,返回值是1。 这些结果说明如果第一个字符串在字母表中的顺序先于第二个字符串,则strcmp ()函数返回的是负数; 相反,返回的就是正数。因此,比较"C"和”A”得到的是1。其他系统可能返回的是2,即二者的ASCII编码 值之差。ANSI标准规定,如果第一个字符串在字母表中的顺序先于第二个字符串,strcmp ()返回-个负 数;如果两个字符串相同,它返回0;如果第一个字符串在字母表中的顺序落后于第二个字符串,它返回一 个正数。而确切的数值是依赖于不同的C实现的。

       strncmp ()变种

       strcmp()函数比较字符串时,一直比较到找到不同的相应字符,搜索可能要进行到字符串结尾处。而 strncmp ()函数比较字符串时,可以比较到字符串不同处,也可以比较完由第三个参数指定的字符数。例如, 如果想搜索以”astro”开头的字符串,您可以限定搜索前5个字符。

/* starsrch.c --使用 strncmp ()函数 */
#include <stdio.h>
#include <string.h>
#define LISTSIZE 5 
int main (void)
{
char * list[LISTSIZE] ={
"astronomy", "astounding",
"astrophysics", "ostracize",
"asterism" 
};
int count = 0;
 int i;
for (i = 0;i < LISTSIZE;i++)
if (strncmp (list[i], "astro", 5) == 0)
{
printf ("Found: %s\n", list[i]);
 count++;
}
printf ("The list contained %d words beginning"
"with astro.\n", count);
return 0;
}

输出如下:
Found: astronomy 

Found: astrophysics
The list contained 2 words beginning with astro.







0 0
原创粉丝点击