C++字符串操作集合

#include <iostream>
using namespace std;
//实现一个函数求字符串的长度。
int my_length(const char *s)
{
    if (*s == '\0')return 0;
    else
        return 1+my_length(s + 1);
}
int main()
{
    char *s = "123456";
    cout << my_length(s) << endl;
    return 0;
}

#include <iostream>
#include <assert.h>
using namespace std;
//实现一个求字符串的长度。
int my_length(const char *s)
{
    if (s == NULL)return 0;
    int count = 0;
    while (s[++count] != '\0');
    return count;
}
int main()
{
    char *s = "";
    cout << my_length(s) << endl;
    return 0;
}


#include <iostream>
#include <string.h>
#include <assert.h>
using namespace std;

char* my_strcpy(char *dist,const char *scour)
{
    assert(scour!=NULL);
    char *p = dist;
    while (*dist++ = *scour++);
    return p;
}
int main()
{
    char *s1 = "123";
    char *s2 = new char[strlen(s1)];
    cout << my_strcpy(s2, s1) << endl;
    return 0;
}

#include <iostream>
#include <assert.h>
using namespace std;
//实现库函数strcat。
char * my_strcat(char *dist,char const *scour)
{
    assert(dist!=NULL || scour!=NULL);
    if (*scour == '\0')return dist;
    char *p = dist;
    while (*dist != '\0')dist++;
    while (*dist++ = *scour++);
    return p;
}
int main()
{
    char *s1 = new char[10];
    strcpy(s1,"123");
    cout << my_strcat(s1,"456")<<endl;
    return 0;
}

#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;
//编写程序使字符串逆序。
char* my_invert(char *s)
{
    assert(s != NULL);
    char *head = s;
    char *last = s+strlen(s)-1;
    char temp;
    while (head < last)
    {
        temp = *head;
        *head = *last;
        *last = temp;
        head++;
        last--;
    }
    return s;
}
int main()
{
    char *s = new char[10];
    strcpy(s,"12345");
    cout << my_invert(s) << endl;
    return 0;
}
#include <iostream>
#include <assert.h>
using namespace std;
//模拟实现strchr函数,功能:在一个字符串中查找一个字符第一次出现的位置,如果没有出现返回NULL。
int my_strchar(const char* dist, char ch)
{
    assert(dist!=NULL);
    int count = 0;
    while (*dist != '\0' && *dist!=ch)
    {
        count++;
        dist++;
    }
    if (*dist == '\0')return 0;
    return count+1;
}
int main()
{
    cout << my_strchar("1234", '1') << endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值