、串的基本操作 ●对于串的基本操作,许多高级语言均提供了相应的运算或 标准库函数来实现。下面仅介绍几种在c语言中常用的串 运算,其它的串操作见相应的文件 定义下列几个变量: ● char s1[20]=“ dirtreeformat”,s2[20]=“ fille. mem char s3[30],p; int result (1)求串长 length) ● int strlen( chars);∥串的长度 例如: printf(%d02 strlen(s1);输出13 北京邮电大学自动化学院
北京邮电大学自动化学院 11 ⚫ 对于串的基本操作,许多高级语言均提供了相应的运算或 标准库函数来实现。下面仅介绍几种在 C语言中常用的串 运算,其它的串操作见相应的文件。 三、串的基本操作 ⚫ 定义下列几个变量: ⚫ char s1[20]=“dirtreeformat”,s2[20]=“file.mem”; ⚫ char s3[30],*p; int result; ⚫ (1)求串长(length) ⚫ int strlen(char s); //求串的长度 ⚫ 例如:printf(“%d”,strlen(s1)); 输出13
、串的基本操作 o char s1[20]=dirtreeformat', s2[20]=file. mem e char s3[30]p; int result (2)串复制(copy) o char *strcpy(char to, char from) ●该函数将串from复制到串to中,并且返回一个指 向串to的开始处的指针。 ●例如: strcpy(s3,s1);∥s3= dirtreeformat 北京邮电大学自动化学院
北京邮电大学自动化学院 12 ⚫ (2)串复制(copy) ⚫ char *strcpy(char to,char from); 三、串的基本操作 ⚫ char s1[20]=“dirtreeformat”,s2[20]=“file.mem”; ⚫ char s3[30],*p; int result; ⚫ 该函数将串from复制到串to中,并且返回一个指 向串to的开始处的指针。 ⚫ 例如:strcpy(s3,s1); //s3=“dirtreeformat
、串的基本操作 ● char s1[20]= dirtreeformat",s2[20]=“ file, men” e char s3[30]p; int result (3)联接( concatenation) char strcat(char to, char from) 该函数将串from复制到串to的末尾,并且返回一指向串 to的开始处的指针。 例如: strcat(s3,”P) ● strcat(s3,s2);∥s3=‘ dirtreeformat/file, mem 北京邮电大学自动化学院 13
北京邮电大学自动化学院 13 ⚫ (3)联接(concatenation) ⚫ char s1[20]=“dirtreeformat”,s2[20]=“file.mem”; ⚫ char s3[30],*p; int result; 三、串的基本操作 ⚫ char strcat(char to,char from) ⚫ 该函数将串from复制到串to的末尾,并且返回一指向串 to的开始处的指针。 ⚫ 例如:strcat(s3,”/”) ⚫ strcat(s3,s2); //s3=“dirtreeformat/file.mem
、串的基本操作 char s120]=“ dirtreeformat,s2[20]=“ fille. men”; char s3[30],*p; int result; (4)串比较( compare) int strcmp(chars1, char s2 ●该函数比较串s1和串s2的大小,当返回值小于0,等于0或大于 0时,分别表示s1s2、s1=s2或s1>s2 ·例如: result= strcmp(“ baker”,”bake”) result>0 ● result= strcmp(12”;”12”); result=0 ● result= strcmp(Joe”,“ Joseph"); result<0 北京邮电大学自动化学院 14
北京邮电大学自动化学院 14 ⚫ (4)串比较(compare) 三、串的基本操作 ⚫ char s1[20]=“dirtreeformat”,s2[20]=“file.mem”; ⚫ char s3[30],*p; int result; ⚫ int strcmp(chars1,char s2); ⚫ 该函数比较串s1和串s2的大小,当返回值小于0,等于0或大于 0时,分别表示s1<s2、s1=s2或s1>s2 ⚫ 例如:result=strcmp(“baker”,”bake”) result>0 ⚫ result=strcmp(“12”,”12”); result=0 ⚫ result=strcmp(“Joe”, “Joseph”); result<0
、串的基本操作 char s1[20]=“ dirtreeformat”,s2[20]= fille, mem”; char s3[30],*p; int result; (5)字符定位 (index) char strchr(char s, char c); 该函数是找c在字符串中第一次出现的位置,若找到则返回该 位置,否则返回NULL 例如:p= strchr((s2,“”);p指向“file”之后的位置 ●if(p) strcpy(p,"‘,cpp");s2=“fle.cpp 北京邮电大学自动化学院
北京邮电大学自动化学院 15 ⚫ (5)字符定位(index) 三、串的基本操作 ⚫ char s1[20]=“dirtreeformat”,s2[20]=“file.mem”; ⚫ char s3[30],*p; int result; ⚫ char strchr(char s,char c); ⚫ 该函数是找c在字符串中第一次出现的位置,若找到则返回该 位置,否则返回NULL。 ⚫ if(p) strcpy( p, “.cpp”); s2=“file.cpp” ⚫ 例如:p=strchr(s2, “.”); p 指向“file”之后的位置