C语言字符串函数 #

一、字符串长度 #

1.1 strlen #

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

int main() {
    char str[] = "Hello";
    printf("长度: %zu\n", strlen(str));
    return 0;
}

二、字符串复制 #

2.1 strcpy #

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

int main() {
    char src[] = "Hello";
    char dest[20];
    strcpy(dest, src);
    printf("复制后: %s\n", dest);
    return 0;
}

2.2 strncpy #

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

int main() {
    char src[] = "Hello World";
    char dest[6];
    strncpy(dest, src, 5);
    dest[5] = '\0';
    printf("复制后: %s\n", dest);
    return 0;
}

三、字符串连接 #

3.1 strcat #

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

int main() {
    char str[20] = "Hello";
    strcat(str, " World");
    printf("连接后: %s\n", str);
    return 0;
}

四、字符串比较 #

4.1 strcmp #

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

int main() {
    char s1[] = "apple";
    char s2[] = "banana";
    
    int result = strcmp(s1, s2);
    if (result < 0) {
        printf("s1 < s2\n");
    } else if (result > 0) {
        printf("s1 > s2\n");
    } else {
        printf("s1 == s2\n");
    }
    return 0;
}

五、字符串查找 #

5.1 strchr #

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

int main() {
    char str[] = "Hello World";
    char* p = strchr(str, 'o');
    if (p) {
        printf("找到: %s\n", p);
    }
    return 0;
}

5.2 strstr #

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

int main() {
    char str[] = "Hello World";
    char* p = strstr(str, "World");
    if (p) {
        printf("找到: %s\n", p);
    }
    return 0;
}

六、总结 #

函数 功能
strlen 字符串长度
strcpy 复制字符串
strcat 连接字符串
strcmp 比较字符串
strchr 查找字符
strstr 查找子串

下一步,让我们学习字符串操作!

最后更新:2026-03-26