首页 > 代码库 > Linux C 程序 (12)

Linux C 程序 (12)

字符串函数
C语言的字符串处理函数
1.puts函数

1 //把一个以‘\0‘结尾的字符串输出到屏幕2 char a[] = "Welcome to";3 char *p = "Linux C Program";4 puts(a);5 puts(p);

2.gets函数

1 //从终端输入一个字符数组,返回字符数组的首地址2 char string[20];3 gets(string);4 puts(string);5 //warning: the `gets‘ function is dangerous and should not be used.6 //系统不推荐使用gets方法了,危险

3.strcpy和strncpy

1 #include<string.h>2 char *strcpy(char *dest , char *src);3 char *strncpy(char *dest , char *src ,int n);//复制前n个字符4 //strcpy是string copy缩写,使用这两个函数必须包含string.h,返回值都是dest5 //复制时连同‘\0‘一起被复制

复制错误代码示范:

1 char a[] = "Linux C Program " , b[20];2 b = a ;3 //字符串复制只能使用strcpy等类似功能的函数

strcpy不安全,容易被黑客利用,一般用strncpy
示例代码:

1 char *s = "hello worlg";2 char d1[20],d2[20];3 strcpy(d1,s);4 strncpy(d2,s,sizeof(s));5 //6 //strncpy复制不完全。。。

4.strcat 和strncat

1 #include<string.h>2 char *strcat(char *dest , char *src);3 char *strncat(char *dest , char *src ,int n);//复制前n个字符4 //把输入的src追加到dest的尾部5 //strcat不安全

5.strcmp    和 strncmp

1 #include<string.h>2 char *strcmp(char *s1 , char *s2);//比较两个字符串3 char *strncmp(char *s1 , char *s2 ,int n);//比较前n字符串4 //第一次出现不同字符时,s1-s2的差值为返回值

6.strlen

 1 #include<string.h> 2 //返回字符串的实际长度,不会包括结束符‘\0‘,sizeof(s)的计算会包含结束符 

7.strlwr 和 strupr//string lower 和string upper的缩写

8.strstr 和 strchr

 1 #include<string.h> 2 char *strstr(char *s1 , char *s2);//s1中寻找s2,返回首次出现指向s2位置的指针,没有找到返回NULL 3 char *strchr(char *s1 , char c);//s1寻找c首次出现的位置,返回指针,没有返回NULL 4 //---- 5 #include<stdio.h> 6 #include<string.h> 7  8 int main(){ 9         char *s1 = "Liunx C Program",*s2="unx",*p;10 11         p = strstr(s1,s2);12         if(p != NULL){13                 printf("%s\n",p);14         }else{15                 printf("not found !");16         }17 18         p= strchr(s1,C);19         if(p != NULL){20                 printf("%s\n",p);21         }else{22                 printf("not found!");23         }24         return 0;25 }

 

Linux C 程序 (12)