作业2.12

用指针实现strlen、strcpy、strcat、strcmp

#include

size_t my_strlen(const char *str) {
    size_t len = 0;
    while (*str != '\0') {
        len++;
        str++;
    }
    return len;
}

int main() {
    char str[] = "Hello, World!";
    printf("Length of string is: %zu\n", my_strlen(str));
    return 0;
}

 

#include

char *my_strcpy(char *dest, const char *src) {
    char *original_dest = dest;
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';  // 添加终止字符
    return original_dest;
}

int main() {
    char src[] = "Hello, World!";
    char dest[50];
    my_strcpy(dest, src);
    printf("Copied string is: %s\n", dest);
    return 0;
}

 

 

#include

char *my_strcat(char *dest, const char *src) {
    char *original_dest = dest;
    while (*dest != '\0') {
        dest++;
    }
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';  // 添加终止字符
    return original_dest;
}

int main() {
    char dest[] = "Hello, ";
    char src[] = "World!";
    my_strcat(dest, src);
    printf("Concatenated string is: %s\n", dest);
    return 0;
}

 

 

#include

int my_strcmp(const char *str1, const char *str2) {
    while (*str1 && (*str1 == *str2)) {
        str1++;
        str2++;
    }
    return *(const unsigned char *)str1 - *(const unsigned char *)str2;
}

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    int result = my_strcmp(str1, str2);
    if (result == 0) {
        printf("Strings are equal.\n");
    } else if (result < 0) {
        printf("First string is less than second string.\n");
    } else {
        printf("First string is greater than second string.\n");
    }
    return 0;
}

 

 

写一个swap函数实现两数交换

#include
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 5;
    int y = 10;

    printf("Before swap: x = %d, y = %d\n", x, y);
    swap(&x, &y);

    printf("After swap: x = %d, y = %d\n", x, y);

    return 0;
}

你可能感兴趣的:(c语言)