一、字符串追加
1.1 库函数srecat的使用

1.2 库函数strncat的使用

1.3 模拟实现库函数 strcat 及 strncat
由上可知,字符串追加的原理是找到所添加字符串的 \0 位置,再对其进行添加。
代码1、


代码2、

二、字符串查找
2.1 库函数strstr的使用
使用strstr函数可以快速的定位到所查找字符串的地址。


2.2 模拟实现库函数 strstr
//模拟实现字符串查找
#include<stdio.h>
char* my_strstr(const char* a,const char* b){
const char* a1 = a;
const char* b1 = b;
const char* p = a; // 记录从字符串a开始查找的位置
if(*b == '\0'){
return (char*)a;
}
while(*p){
a1 = p;
b1 = b; // 重置指向字符串b的指针
while(*a1 && *b1 && (*a1 == *b1)){
a1++;
b1++;
}
if(*b1 == '\0'){ //表示已查完,返回开始查找的位置
return (char*)p;
}
p++;
}
return NULL; //未查找到
}
int main(){
char a[20] = "hongshaorou";
char b[] = "shao";
char * ret = my_strstr(a,b);
if(ret == NULL){
printf("没找到");
}else{
printf("找到了:%s\n",ret);
}
return 0;
}
三、求字符串长度
3.1 库函数strlen的使用
记录 ' \0 ' 之前的字符数。

3.2 模拟实现库函数strlen

注意:在库函数中strlen的返回类型为suze_t(无符号整型),我们这里的返回类型为int型。
代码1
#include<stdio.h>
int my_strlen(const char* a){
int count = 0;
while(*a){
a++;
count++;
}
return count;
}
int main(){
char a[] = "hello";
int len = my_strlen(a);
printf("%d\n",len);
return 0;
}
代码2
#include<stdio.h>
int my_strlen(const char* a){
const char* p = a;
while(*a){
a++;
}
return (int)(a-p);
}
int main(){
char a[] = "hello";
int len = my_strlen(a);
printf("%d\n",len);
return 0;
}