字符串函数接口

Bzero()会将参数s所指的内存区域前n个字节,全部设为零值。

Memset()把c字符填入s所在的地址中,填入n个。

Strcat()会将参数src字符串拷贝到参数dest所指的字符串尾。(第一个参数a要有足够的空间来容纳要拷贝的字符串)这个是系统原函数的说明,我写的不用担心这个。

Strcmp()用来比较参数s1和s2字符串。如果相等返回 0 如果不相等返回非 0

Strcp()会将参数b字符串拷贝至参a所指的地址。

Strncpy()会将参数b字符串拷贝前n个字符至参数a所指的地址。

Strlen()用来计算指定的字符串s的长度,不包括结束字符"\0"。

Strstr()会从字符串a中搜寻字符串b,并将第一次出现的地址返回。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void Bzero(char *str,int n)
{
    int i = 0;
    for (i = 0; i < n; i++)
    {
        str[i] = '\0';
    }
}

void Memset(char *str, char ch, int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        str[i] = ch;
    }
}

void Strcat(char *a, char *b)
{
    int j = 0, k = 0;
    int n = 0;
    while (*a++)
    {
        j++;
    }
    a -= j + 1; // 回到首地址
    while (*b++)
    {
        k++;
    }
    b -= k + 1;
    a[j + k]; // 定义新数组以防止连接起后溢出
    // printf("%s ",a);
    // printf("%c",str[j-1]);
    for (int i = j; i <= j + k; i++)
    {
        a[i] = b[n];
        n++;
    }
}

int Strcmp(char *a, char *b)
{
    while (*a == *b)
    {
        if (*a == '\0' && *b == '\0')
            return 0;
        a++;
        b++;
    }
    return -1;
}

char *Strcpy(char *a, char *b)
{
    if ((a == NULL) || (b == NULL))

        return NULL;

    char *str = a;

    while ((*str++ = *b++) != '\0');

    return b;
}

char *Strncpy(char *a, const char *b, int n)
{
    for (int i = 0; i < n; i++)
    {
        a[i] = b[i];
    }
}

int Strlen(char *a)
{
    int j = 0;
    while (*a++)
        j++;
    a -= j + 1; // 回到首地址
    return j;
}

char *Strstr(char *a, char *b)
{
    printf("this is me\n");
    int j = 0, flag = 0;
    while (*b++)
    {
        j++;
    }
    b -= j + 1; // 回到首地址
    // printf("%d\n", j);
    while (*a != '\0')
    {
        if (*b == *a)
        {
            for (int i = 0; i < j; i++)
            {
                if (*a == *b)
                {
                    a++;
                    b++;
                    flag++;
                }
                else break;
            }
        }
        else
        a++;
    }

    if (flag == j)
    {
        a -= 2*flag+1;
        return a;
    }
    else
        return 0;
}

int main()
{
    char str1[] = "ghmmgjgh";
    char str2[] = "1234567899";
    // Bzero(str1,3);
    // Memset(str1,'h',2);
    // Strcat(str1,str2);
    // int x = Strcmp(str1, str2);
    // Strcpy(str1, str2 + 5);
    // Strncpy(str1,str2,4);
    // int y = Strlen(str1);
    // 字符串查找
    char str[1024] = {"123qwe456asdqqq"};
    char *p = Strstr(str, "wesa");
    if (p == NULL)
    {
        printf("无此字符串\n");
        return 0;
    }
    printf("%s\n", p);
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值