1. 程式人生 > >嘗試實現strlen(),strcpy(),strcat(),strcmp()

嘗試實現strlen(),strcpy(),strcat(),strcmp()

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define LL long long

//strlen(),strcpy(),strcat(),strcmp()

int _strlen(char s[])
{
    int i = 0;
    while(s[i] != '\0') i++;
    return i;
}
int _strcpy(char s1[], char s2[])
{
    int i = 0;
    while(s1[i] != '\0'){
        s1[i] = s2[i];
        i++;
    }
    return 0;
}
int _strcat(char s1[], char s2[])
{
    int s1_len = 0, s2_len = 0;
    while(s1[s1_len] != '\0') s1_len++;
    while(s2[s2_len] != '\0'){
        s1[s1_len + s2_len] = s2[s2_len];
        s2_len++;
    }
    return 0;
}
int _strcmp(char s1[], char s2[])
{
    int s1_len = 0, s2_len = 0, k = 0;
    while(s1[s1_len] != '\0') s1_len++;
    while(s2[s2_len] != '\0') s2_len++;
    if(s1_len == s2_len){
        for(int i = 0; i < s1_len; i++){
            if(s1[i] == s2[i]) k++;
            else if(s1[i] > s2[i]) return 1;
            else if(s1[i] < s2[i]) return-1;
        }
        if(k == s1_len) return 0;
    }
    else if(s1_len > s2_len) return 1;
    else if(s1_len < s2_len) return -1;
}
int main()
{
    char s[] = "abcde", c[] = "fghij";
    printf("%d\n", _strlen(s));

    _strcpy(s, c);
    printf("%s\n", s);

    _strcat(s,c);
    printf("%s\n", s);

    printf("%d\n", _strcmp(s, c));
    return 0;
}

在這裡插入圖片描述