C语言中的字符串函数:从基础到高级的详解

2024-02-26 0 298

在C语言中,字符串是一系列字符的**,以空字符’\0’作为结束标志,字符串在C语言中通常表示为字符数组,而字符串函数则是用来处理这些字符数组的,这些函数主要在<string.h>头文件中定义,下面我们将详细介绍一些常用的C语言字符串函数。

1、strlen()

strlen()函数用于返回字符串的长度,不包括终止字符’\0’。

#include <stdio.h>
#include <string.h>
int main() {
    char str[] = "Hello, world!";
    printf("The length of the string is: %lu\n", strlen(str));
    return 0;
}

输出:

The length of the string is: 13

2、strcpy()

strcpy()函数用于将一个字符串**到另一个字符串。

#include <stdio.h>
#include <string.h>
int main() {
    char src[] = "Hello, world!";
    char dest[20];
    strcpy(dest, src);
    printf("Copied string: %s\n", dest);
    return 0;
}

输出:

Copied string: Hello, world!

3、strcat()

strcat()函数用于将一个字符串连接到另一个字符串的末尾。

#include <stdio.h>
#include <string.h>
int main() {
    char str1[] = "Hello, ";
    char str2[] = "world!";
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);
    return 0;
}

输出:

Concatenated string: Hello, world!

4、strcmp()

strcmp()函数用于比较两个字符串,如果两个字符串相等,则返回0;如果第一个字符串小于第二个字符串,则返回负值;如果第一个字符串大于第二个字符串,则返回正值。

相关文章

猜你喜欢
官方客服团队

为您解决烦忧 - 24小时在线 专业服务

  • 0 +

    访问总数

  • 0 +

    会员总数

  • 0 +

    文章总数

  • 0 +

    今日发布

  • 0 +

    本周发布

  • 4975 +

    运行天数

你的前景,远超我们想象