当前位置:首页 C++ > 正文

c++字符数组表示的字符串函数

作者:野牛程序员:2023-07-29 16:43:21 C++阅读 2603

在C++中,字符数组可以用于表示字符串,并且可以使用一些字符串函数来对字符数组(字符串)进行操作。

  1. strlen:计算字符串的长度,不包括空字符('\\0')。

  2. #include <cstring>
    char str[] = "Hello";
    int length = strlen(str); // 结果为5,不包括空字符
  3. strcpy:复制字符串到目标字符数组中。

    #include <cstring>
    
    char source[] = "Hello";
    char destination[20];
    strcpy(destination, source); // 复制source到destination
  4. strcat:连接两个字符串,将第二个字符串追加到第一个字符串的末尾。

  5. #include <cstring>
    char str1[] = "Hello";
    char str2[] = " World";
    strcat(str1, str2); // 连接结果为"Hello World"
  6. strcmp:比较两个字符串,根据字典顺序返回一个整数。

  7. #include <cstring>
    char str1[] = "apple";
    char str2[] = "banana";
    int result = strcmp(str1, str2); // 结果为负数,因为"apple"在字典顺序上比"banana"小
    • 返回值为0:表示两个字符串相等。

    • 返回值小于0:表示第一个字符串小于第二个字符串。

    • 返回值大于0:表示第一个字符串大于第二个字符串。

  8. strstr:在字符串中搜索子字符串,并返回子字符串第一次出现的位置。

  9. #include <cstring>
    char str[] = "Hello, World!";
    char sub[] = "World";
    char* position = strstr(str, sub); // 返回"World!"在str中的位置
  10. strchr:在字符串中搜索指定字符,并返回第一次出现的位置。

  11. #include <cstring>
    char str[] = "Hello, World!";
    char ch = 'o';
    char* position = strchr(str, ch); // 返回'o'在str中的位置
  12. strtok:将字符串分割成多个子字符串,使用指定的分隔符进行分割。

    #include <cstring>
    
    char str[] = "apple,banana,orange";
    char delimiter[] = ",";
    char* token = strtok(str, delimiter); // 返回"apple",并在str中插入'\\0'作为结束符
    while (token != nullptr) {
        // 继续获取下一个子字符串
        token = strtok(nullptr, delimiter);
    }
  13. memset:将字符数组(字符串)中的每个字符都设置为指定的值。

  14. #include <cstring>
    char str[10];
    memset(str, 'A', sizeof(str)); // 将str中的每个字符都设置为'A'
  15. memcpy:将源字符数组(字符串)中的内容复制到目标字符数组中。

  16. #include <cstring>
    char source[] = "Hello";
    char destination[10];
    memcpy(destination, source, sizeof(source)); // 将source复制到destination
  17. memcmp:比较两个字符数组(字符串)的前n个字符,根据字典顺序返回一个整数。

  18. #include <cstring>
    char str1[] = "apple";
    char str2[] = "banana";
    int n = 3;
    int result = memcmp(str1, str2, n); // 比较前3个字符,结果为负数,因为"app"在字典顺序上比"ban"小
  19. strncpy:复制源字符数组(字符串)的前n个字符到目标字符数组中,如果不够n个字符则用空字符填充。

  20. #include <cstring>
    char source[] = "Hello";
    char destination[10];
    int n = 5;
    strncpy(destination, source, n); // 复制前5个字符,目标数组中剩余位置用'\\0'填充
  21. strncat:连接两个字符串的前n个字符,将第二个字符串的前n个字符追加到第一个字符串的末尾。

  22. #include <cstring>
    char str1[] = "Hello";
    char str2[] = " World";
    int n = 5;
    strncat(str1, str2, n); // 连接前5个字符,结果为"Hello World"
  23. sprintf:将格式化的数据写入字符串中,类似于printf,但输出到字符数组(字符串)。

  24. #include <cstdio>
    char str[20];
    int num = 123;
    sprintf(str, "Number: %d", num); // 将格式化数据写入str,结果为"Number: 123"
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击