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

本文详细介绍了C++中常用的字符串操作函数,包括strlen用于计算字符串长度,strcpy和strncpy实现字符串复制,strcat进行字符串拼接,以及strcmp进行字符串比较。通过实例展示了每个函数的使用方法,并强调了strncpy的安全性及使用注意事项。
摘要由CSDN通过智能技术生成


前言

本文使用的字函数返回类型中的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短

总结

求个关注一起学习呀!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zedkyx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值