字符串处理函数

xiaoxiao2021-02-28  19

用字符串处理函数时我们常使用string.h中的库函数来实现求字符串的长度、字符串的连接、复制和比较等操作,下面我们来看看如果不使用这些库函数它是如何实现的。 1、求字符串的长度strlen(str)

    功能:统计以str为起始地址的字符串的长度,长度不包括字符串的结束标志'\0',将其长度作为函数值返回。

#include <stdio.h> #include <assert.h> int Mystrlen(const char *str) { assert(str != NULL); if(str == NULL) { return -1; } int i = 0; for(i=0;str[i]!='\0';i++) { i++; } return i; } int main() { char str1[10] = "abcd"; printf("%d\n",Mystrlen(str1));//4 printf("%d\n",Mystrlen(""));//0 return 0; }2、字符串连接函数strcat(str1,str2)     功能:将以str2首地址起的字符串连接到str1字符串的后面,从str1原来的'\0'处开始连接。     str1一般为字符数组,要有足够的空间,以确保连接字符串后不越界;

    str2可以是字符数组名、字符串常量或指向字符串的字符指针。

#include <stdio.h> #include <assert.h> char *Mystrcat(char *str1,const char *str2) { assert(str1!=NULL && str2!=NULL); char *p=str1; while(*str1!='\0')// 找str1的尾巴 { str1++; } while(*str1++=*str2++); return p; } int main() { char str1[20]="hello"; char str2[20]=" everybody!"; char *q=" everyone!"; //Mystrcat(str1,str2); //printf("%s\n",str1); //输出hello everybody! //Mystrcat(str1," world!"); //printf("%s\n",str1); //输出hello world! Mystrcat(str1,q); printf("%s\n",str1); //输出hello everyone! return 0; }

3、字符串复制函数strcpy(str1,str2)    功能:将以str2为首地址的字符串复制到以str1为首地址的字符数组中。    str1一般为字符数组,要有足够的空间,以确保复制字符串后不越界;    str2可以是字符数组名、字符串常量或指向字符串的字符指针。下面两种方法都可以实现字符串的复制

#include <stdio.h> #include <assert.h> void Mystrcpy(char *str1,const char *str2) { assert(str1!=NULL&&str2!=NULL); if(str1==NULL||str2==NULL) { return ; } while(*str2!='\0') { *str1++=*str2++;//*(str1++)=*(str2++); } *str1='\0'; } void Mystrcpy1(char *des,const char *src) { while(*des++=*src++); } int main() { char str1[20]="hello"; char str2[20]="everybody!"; char *q="everyone!"; //Mystrcpy(str1,str2); //printf("%s\n",str1); //输出everybody! //Mystrcpy(str1,"world!"); //printf("%s\n",str1); //输出world! Mystrcpy(str1,q); printf("%s\n",str1); //输出everyone! return 0; }4、字符串比较函数strcmp(str1,str2)     功能:对以str1和str2为首地址的两个字符串进行比较,比较的结果由返回值表示。     当str1=str2时,函数的返回值为0;当str1<str2时,函数的返回值为负整数(绝对值是ASCII码的差值);当str1>str2时,函数 的返回值为正整数(绝对值是ASCII码的差值)。

    字符串之间的比较规则:从第一个字符开始,对两个字符串对应位置的字符按ASCII码的大小进行比较,直到出现第一个不同的字符为止,即由这两个字符的大小决定其所在串的大小。    字符串或(字符数组)之间不能直接比较,但是通过此函数,可以间接达到比较的效果。

#include <stdio.h> #include <assert.h> int Mystrcmp(const char *str1,const char *str2) { int gap; while((gap=*str1-*str2)==0 && *str1!='\0') { str1++; str2++; } return gap; } int main() { printf("%d\n",Mystrcmp("abcde","abcde"));//0 printf("%d\n",Mystrcmp("abcde","abcd"));//101 printf("%d\n",Mystrcmp("abcd","abcde"));//-101 return 0; }
转载请注明原文地址: https://www.6miu.com/read-1750123.html

最新回复(0)