3.字符串連接函數strcat
格式:strcat(字符數組名1,字符數組名2)
功能:把字符數組2中的字符串連接到字符數組1中字符串的後麵,並刪去字符串1後的字符串結束標誌符“\0”。要求字符數組1的長度要能滿足連接後的長度。字符數組2也可以是一個字符串常量。
[例710]字符串連接。
#include
#include
voidmain()
{
charflower[100];
charaddstr[]="ismyfavoriteflower,too.";
puts("What’syourfavoriteflower?");
gets(flower);
strcat(flower,addstr);
puts(flower);
}
程序運行結果:
What’syourfavoriteflower?
Rose
Roseismyfavoriteflower,too.
4.字符串拷貝函數strcpy
格式:strcpy(字符數組名1,字符數組名2)
功能:把字符數組2中的字符串拷貝到字符數組1中,包括字符數組2中的“\0”也一同拷貝。字符數組2也可以是一個字符串常量。用戶必須保證字符數組1有足夠的長度,否則不能全部裝入所拷貝的字符串。
[例711]字符串拷貝。
#include
#include
voidmain()
{charoldword[50],newword[50];
puts("What’sthenewwordyou’velearnedtoday?");
gets(newword);
strcpy(oldword,newword);
printf("Good,\"%s\"isanoldwordforyounow.\n",oldword);
}
程序運行結果:
What’sthenewwordyou’velearnedtoday?
honest
Good,"honest"isanoldwordforyounow.
5.字符串比較函數strcmp
格式:strcmp(字符數組名1,字符數組名2)
功能:按照ASCII碼順序比較兩個數組中的字符串,並由函數返回值返回比較結果。
字符串1=字符串2,返回值=0;
字符串1>字符串2,返回值>0;
字符串1
#include
#defineANSWER"beijing"/*給定答案*/
voidmain()
{chartry[50];
intflag;
puts("What’sthecapitalofChina?");
gets(try);
flag=strcmp(try,ANSWER);/*與答案比較*/