欢迎访问宙启技术站
智能推送

常见的字符串操作函数实例演示

发布时间:2023-06-05 09:32:53

字符串操作函数在编程中经常被使用,它可以方便地对字符串进行操作和处理。下面给出一些常见的字符串操作函数的实例演示:

1. strlen

strlen函数返回一个字符串的长度,即它包含的字符数。

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

int main()
{
    char str[] = "Hello, world!";
    int len = strlen(str);
    printf("The length of the string is: %d
", len);
    return 0;
}

输出结果:

The length of the string is: 13

2. strcpy

strcpy函数用来将一个字符串复制到另一个字符串中。

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

int main()
{
    char str1[] = "Hello, world!";
    char str2[20];
    strcpy(str2, str1);
    printf("The copied string is: %s
", str2);
    return 0;
}

输出结果:

The copied string is: Hello, world!

3. strcat

strcat函数用来将两个字符串连接起来。

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

int main()
{
    char str1[] = "Hello, ";
    char str2[] = "world!";
    strcat(str1, str2);
    printf("The concatenated string is: %s
", str1);
    return 0;
}

输出结果:

The concatenated string is: Hello, world!

4. strcmp

strcmp函数用来比较两个字符串是否相等。

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

int main()
{
    char str1[] = "Hello, world!";
    char str2[] = "Hello, world!";
    int result = strcmp(str1, str2);
    if (result == 0)
    {
        printf("The two strings are equal.
");
    }
    else
    {
        printf("The two strings are not equal.
");
    }
    return 0;
}

输出结果:

The two strings are equal.

5. strchr

strchr函数用来查找一个字符在字符串中 次出现的位置。

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

int main()
{
    char str[] = "Hello, world!";
    char search = 'o';
    char *result = strchr(str, search);
    if (result != NULL)
    {
        printf("The character '%c' is found at position %ld.
", search, result - str + 1);
    }
    else
    {
        printf("The character '%c' is not found.
", search);
    }
    return 0;
}

输出结果:

The character 'o' is found at position 5.

6. strstr

strstr函数用来查找一个字符串在另一个字符串中 次出现的位置。

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

int main()
{
    char str1[] = "Hello, world!";
    char str2[] = "world";
    char *result = strstr(str1, str2);
    if (result != NULL)
    {
        printf("The string '%s' is found at position %ld.
", str2, result - str1 + 1);
    }
    else
    {
        printf("The string '%s' is not found.
", str2);
    }
    return 0;
}

输出结果:

The string 'world' is found at position 8.

这些函数是使用频率较高的字符串操作函数,在编程中经常会用到。通过这些例子的演示,读者可以更加深入地了解这些函数的用法和作用,为自己以后的编程工作打下坚实的基础。