c/c++字符串基本函数实现

120 阅读1分钟

文章目录


前言

本文使用的字函数返回类型中的size_t是一个typedef名字,表示一种无符号整型。
测试数据在函数下方。


一、头文件

#include <iostream>
#include <cstring>//<string.h>
using namespace std;
//maybe useful
#include <iomanip>
#include <cstdlib>
#include <conio.h>

二、函数实现

1.strlen(得出字符串长度)

代码如下:

size_t Strlen(const char *s){
    const char *p=s;
    while(*s++){
        ;
    }
    return s-p-1;
}
//or
int Strlen(const char *s){
    int n = 0;
    while(*s++){
        n++;
    }
    return n;
}
int main(){
    char s[]="1234";
    cout<<Strlen(s)<<endl;
}

2.strcpy and strncpy

代码如下:

char *Strcpy(char *s1,const char *s2){
    while(*s1!='\0'){
        *s1++=*s2++;
    }
    return s1;
}
int main(){
    char s1[]="1234";
    char s2[]="abcd";
    cout<<"Before copy: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
    Strcpy(s1,s2);
    cout<<"After copy: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
}

注:strcpy在strlen(s1)<strlen(s2)时只能复制到s1长度为止
strncpy是一种更安全的复制字符串的方法,用第三个参数限制所复制的字符数。

char *Strncpy(char *s1,const char *s2,int n){
    while(n--){
        *s1++=*s2++;
    }
    return s1;
}
int main(){
    char s1[]="1234";
    char s2[]="abcde";
    cout<<"Before copy: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
    Strncpy(s1,s2,sizeof(s1)-1);
    s1[sizeof(s1)-1]='\0';//确保s1总以空字符结束
    cout<<"After copy: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
}

3.strcat(拼接)

代码如下:

char *Strcat(char *s1,const char *s2){
    char *p = s1;
    while(*p)
        p++;
    while(*p++=*s2++){
        ;
    }
    return s1;
}
int main(){
    const int n = 1024;
    char s1[n]="1234";//n>=strlen(s1)+strlen(s2)
    char s2[]="abcde";
    cout<<"Before cat: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
    Strcat(s1,s2);
    cout<<"After cat: \ns1 = "<<s1<<"\ns2 = "<<s2<<endl;
}

4.strcmp(比较)

代码如下:

int Strcmp(const char *s1,const char *s2){
    while ((*s1) && (*s1 == *s2)){
    //若改为(*s1++ == *s2++)会多执行一次自增行为
        *s1++;
        *s2++;
    }	
    return (*s1>*s2)?1:((*s1<*s2)?-1:0);
 
}
int main(){
    char s1[]="1234";
    char s2[]="abcde";
    cout<<Strcmp(s1,s2)<<endl;
}

注:在ASCII码中,65-90表示大写字母,97-122表示小写字母,
48-57表示数字,32代表空格符。
s1小于s2<==>
前i个字符一致,第i+1个字符小或者s1所有字符与s2一致,但s1比s2短

总结

求个关注一起学习呀!