当前位置: 首页 > news >正文

C语言:字符函数和字符串函数

1.字符函数

在 C 语言中,字符分类函数主要定义在<ctype.h>头文件中,这些函数可以用来判断一个字符是否属于特定的字符类别,下面为你详细介绍一些常用的字符分类函数:

1.1 iscntrl

  • 功能:判断一个字符是否为控制字符,控制字符是 ASCII 码表中 0 - 31 以及 127 的字符,一般不显示为可见字符,用于控制设备等特定功能。
  • 原型int iscntrl(int c);,参数c为要检查的字符,其值通常为unsigned char类型或EOF
  • 返回值:若c是控制字符,返回非零值(真);否则返回 0(假)。
#include <stdio.h>
#include <ctype.h>

int main() {
    char testChar = '\n';
    if (iscntrl(testChar)) {
        printf("%c 是控制字符\n", testChar);
    } else {
        printf("%c 不是控制字符\n", testChar);
    }
    return 0;
}

1.2 isspace

  • 功能:判断一个字符是否为空白字符,空白字符包括空格、换页符(\f)、换行符(\n)、回车符(\r)、水平制表符(\t)、垂直制表符(\v)。
  • 原型int isspace(int c);,参数c为待检查字符。
  • 返回值:若c是空白字符,返回非零值(真);否则返回 0(假)。
  • 示例代码
#include <stdio.h>
#include <ctype.h>

int main() {
    char testChar = ' ';
    if (isspace(testChar)) {
        printf("%c 是空白字符\n", testChar);
    } else {
        printf("%c 不是空白字符\n", testChar);
    }
    return 0;
}

1.3 isdigit

  • 功能:检查一个字符是否为十进制数字(0 - 9)。
  • 原型int isdigit(int c);c为要判断的字符。
  • 返回值:如果c是 0 - 9 中的数字字符,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = '5';
        if (isdigit(testChar)) {
            printf("%c 是十进制数字\n", testChar);
        } else {
            printf("%c 不是十进制数字\n", testChar);
        }
        return 0;
    }

1.4 isxdigit

  • 功能:判断一个字符是否为十六进制数字,包括 0 - 9、小写字母 a - f、大写字母 A - F。
  • 原型int isxdigit(int c);,参数c为需要检测的字符。
  • 返回值:若c是十六进制数字字符,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = 'A';
        if (isxdigit(testChar)) {
            printf("%c 是十六进制数字\n", testChar);
        } else {
            printf("%c 不是十六进制数字\n", testChar);
        }
        return 0;
    }

1.5 islower

  • 功能:检测一个字符是否为小写字母(a - z)。
  • 原型int islower(int c);c是要检查的字符。
  • 返回值:如果c是小写字母,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = 'b';
        if (islower(testChar)) {
            printf("%c 是小写字母\n", testChar);
        } else {
            printf("%c 不是小写字母\n", testChar);
        }
        return 0;
    }

1.6 isupper

  • 功能:判断一个字符是否为大写字母,即 A - Z。与islower类似,在进行字母大小写转换等操作时会用到。
  • 头文件#include <ctype.h>
  • 返回值:若字符是大写字母,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char c1 = 'C';
        char c2 = 'c';
        printf("字符 %c 是否为大写字母: %d\n", c1, isupper(c1));
        printf("字符 %c 是否为大写字母: %d\n", c2, isupper(c2));
        return 0;
    }

1.7 isalpha

  • 功能:检测一个字符是否为字母(a - z 或 A - Z)。
  • 原型int isalpha(int c);c为待检测字符。
  • 返回值:如果c是字母,返回非零值(真);否则返回 0(假)。
  • 示例代码
  • #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = 'd';
        if (isalpha(testChar)) {
            printf("%c 是字母\n", testChar);
        } else {
            printf("%c 不是字母\n", testChar);
        }
        return 0;
    }

1.8 isalnum

  • 功能:判断一个字符是否为字母或数字(a - z、A - Z、0 - 9)。
  • 原型int isalnum(int c);c为要检查的字符。
  • 返回值:若c是字母或数字,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = 'e';
        if (isalnum(testChar)) {
            printf("%c 是字母或数字\n", testChar);
        } else {
            printf("%c 不是字母或数字\n", testChar);
        }
        return 0;
    }

1.9  ispunct

  • 功能:检测一个字符是否为标点符号,即不属于数字或字母的可打印图形字符。
  • 原型int ispunct(int c);,参数c为要检测的字符。
  • 返回值:如果c是标点符号,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = '.';
        if (ispunct(testChar)) {
            printf("%c 是标点符号\n", testChar);
        } else {
            printf("%c 不是标点符号\n", testChar);
        }
        return 0;
    }

1.10 isgraph

  • 功能:判断一个字符是否为图形字符(除空格之外的可打印字符,包含字母、数字、标点符号等)。
  • 原型int isgraph(int c);c为要判断的字符。
  • 返回值:若c是图形字符,返回非零值(真);否则返回 0(假)。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = '!';
        if (isgraph(testChar)) {
            printf("%c 是图形字符\n", testChar);
        } else {
            printf("%c 不是图形字符\n", testChar);
        }
        return 0;
    }

1.11 isprint

  • 功能:检测一个字符是否为可打印字符(包括图形字符和空白字符)。
  • 原型int isprint(int c);c为要检查的字符。
  • 返回值:如果c是可打印字符,返回非零值(真);否则返回 0(假)。
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char testChar = 'h';
        if (isprint(testChar)) {
            printf("%c 是可打印字符\n", testChar);
        } else {
            printf("%c 不是可打印字符\n", testChar);
        }
        return 0;
    }

2. 字符转换函数 

1. tolower 和 toupper 函数

这两个函数定义在 <ctype.h> 头文件中,用于将字符在大小写之间进行转换。

函数原型

int tolower(int c); 

int toupper(int c);

1.1 tolower 函数

  • 功能:将大写字母转换为小写字母。如果传入的字符不是大写字母,则直接返回该字符本身。
  • 原型int tolower(int c);
  • 返回值:若 c 是大写字母,返回对应的小写字母;若不是大写字母,返回 c 本身。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char ch = 'B';
        char lower_ch = tolower(ch);
        printf("'%c' 转换为小写后是 '%c'\n", ch, lower_ch);
        return 0;
    }

1.2. toupper 函数

  • 功能:将小写字母转换为大写字母。如果传入的字符不是小写字母,则直接返回该字符本身。
  • 原型int toupper(int c);
  • 返回值:若 c 是小写字母,返回对应的大写字母;若不是小写字母,返回 c 本身。
  • 示例代码
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char ch = 'd';
        char upper_ch = toupper(ch);
        printf("'%c' 转换为大写后是 '%c'\n", ch, upper_ch);
        return 0;
    }

2. atoiatol 和 atof 函数

这些函数定义在 <stdlib.h> 头文件中,用于将字符串转换为整数、长整数和浮点数。

函数原型

int atoi(const char *nptr); 

long atol(const char *nptr); 

double atof(const char *nptr);

2.1 atoi 函数

  • 功能:将字符串转换为整数。它会忽略字符串开头的空白字符,然后将连续的数字字符转换为对应的整数值。遇到非数字字符则停止转换。
  • 原型int atoi(const char *nptr);
  • 返回值:返回转换后的整数值。如果字符串不能转换为有效的整数,则返回 0。
  • 示例代码
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char str[] = "1234";
        int num = atoi(str);
        printf("字符串 '%s' 转换为整数是 %d\n", str, num);
        return 0;
    }

2.2 atol 函数

  • 功能:将字符串转换为长整数。同样会忽略字符串开头的空白字符,把连续数字字符转换为长整数值,遇到非数字字符停止转换。
  • 原型long atol(const char *nptr);
  • 返回值:返回转换后的长整数值。若字符串无法转换为有效的长整数,则返回 0。
  • 示例代码
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char str[] = "567890";
        long num = atol(str);
        printf("字符串 '%s' 转换为长整数是 %ld\n", str, num);
        return 0;
    }

2.3 atof 函数

  • 功能:将字符串转换为双精度浮点数。忽略字符串开头的空白字符,把符合浮点数格式的连续字符转换为双精度浮点数,遇到不符合格式的字符停止转换。
  • 原型double atof(const char *nptr);
  • 返回值:返回转换后的双精度浮点数值。若字符串不能转换为有效的浮点数,则返回 0.0。
  • 示例代码
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char str[] = "3.14159";
        double num = atof(str);
        printf("字符串 '%s' 转换为浮点数是 %f\n", str, num);
        return 0;
    }

3. sprintf 和 snprintf 函数

这两个函数定义在 <stdio.h> 头文件中,用于将格式化的数据写入字符串。

函数原型

int sprintf(char *str, const char *format, ...);

int snprintf(char *str, size_t size, const char *format, ...);

3.1 sprintf 函数

  • 功能:将格式化的数据写入字符串。按照指定的格式将数据组合成一个字符串,并存储到指定的字符数组中。
  • 原型int sprintf(char *str, const char *format, ...);
  • 返回值:返回写入字符串的字符数(不包括终止的空字符 '\0')。如果发生错误,返回负数。
  • 示例代码
#include <stdio.h>

int main() {
    char str[50];
    int num = 20;
    sprintf(str, "数字是 %d", num);
    printf("格式化后的字符串: %s\n", str);
    return 0;
}

3.2 snprintf 函数

  • 功能:将格式化的数据写入字符串,同时可以指定缓冲区的大小,避免缓冲区溢出。当写入的字符数超过缓冲区大小时,会截断数据。
  • 原型int snprintf(char *str, size_t size, const char *format, ...);
  • 返回值:如果返回值为非负且小于 size,表示实际写入的字符数(不包括终止的空字符);如果返回值大于等于 size,表示需要的缓冲区大小(不包括终止的空字符)。
  • 示例代码
    #include <stdio.h>
    
    int main() {
        char str[20];
        int num = 12345;
        int result = snprintf(str, sizeof(str), "数字是 %d", num);
        printf("格式化后的字符串: %s\n", str);
        printf("实际需要的字符数(不包括空字符): %d\n", result);
        return 0;
    }

4. strtolstrtoul 和 strtod 函数

这些函数定义在 <stdlib.h> 头文件中,用于将字符串转换为长整数、无符号长整数和双精度浮点数,并且可以处理不同进制的输入。

函数原型

long strtol(const char *nptr, char **endptr, int base); 

unsigned long strtoul(const char *nptr, char **endptr, int base); 

double strtod(const char *nptr, char **endptr);

4.1 strtol 函数
  • 功能:将字符串转换为长整数,可以处理不同进制(如二进制、八进制、十六进制等)的输入。忽略字符串开头的空白字符,遇到非数字字符或超出指定进制范围的字符停止转换。
  • 原型long strtol(const char *nptr, char **endptr, int base);
  • 返回值:返回转换后的长整数值。如果字符串不能转换为有效的长整数,则返回 0。endptr 指向转换结束后的第一个字符。
  • 示例代码
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char str[] = "1010";
        char *endptr;
        long num = strtol(str, &endptr, 2);
        printf("二进制字符串 '%s' 转换为长整数是 %ld\n", str, num);
        printf("转换结束后的位置: %s\n", endptr);
        return 0;
    }
4.2 strtoul 函数
  • 功能:将字符串转换为无符号长整数,支持不同进制的输入。忽略字符串开头的空白字符,遇到不符合要求的字符停止转换。
  • 原型unsigned long strtoul(const char *nptr, char **endptr, int base);
  • 返回值:返回转换后的无符号长整数值。若字符串无法转换为有效的无符号长整数,则返回 0。endptr 指向转换结束后的第一个字符。
  • 示例代码
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        char str[] = "FF";
        char *endptr;
        unsigned long num = strtoul(str, &endptr, 16);
        printf("十六进制字符串 '%s' 转换为无符号长整数是 %lu\n", str, num);
        printf("转换结束后的位置: %s\n", endptr);
        return 0;
    }
    4.3 strtod 函数
  • 功能:将字符串转换为双精度浮点数。忽略字符串开头的空白字符,遇到不符合浮点数格式的字符停止转换。
  • 原型double strtod(const char *nptr, char **endptr);
  • 返回值:返回转换后的双精度浮点数值。若字符串不能转换为有效的浮点数,则返回 0.0。endptr 指向转换结束后的第一个字符。
    • 示例代码
      #include <stdio.h>
      #include <stdlib.h>
      
      int main() {
          char str[] = "3.14abc";
          char *endptr;
          double num = strtod(str, &endptr);
          printf("字符串 '%s' 转换为浮点数是 %f\n", str, num);
          printf("转换结束后的位置: %s\n", endptr);
          return 0;
      }

总结:
  • C 语言字符转换函数可分三类:
  • 大小写转换<ctype.h>里的tolower转大写为小写,toupper转小写为大写。
  • 字符串转数值<stdlib.h>中的atoiatolatof简单转换字符串为对应数值;strtolstrtoulstrtod能处理不同进制或更复杂的转换,且可指示转换结束位置。
  • 格式化转换<stdio.h>sprintf按格式将数据写入字符串,snprintf能指定缓冲区大小防溢出。

3. 字符串处理函数

以下会讲解一些比较常用的字符串函数

1. strlen

  • 功能:计算字符串的实际长度,即字符串中字符的数量,不包含字符串结束符 '\0'
  • 原型size_t strlen(const char *s);
  • 返回值:返回一个 size_t 类型的值,表示字符串的长度。size_t 是无符号整数类型,通常用于表示对象的大小。
  • 示例代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char str[] = "C Programming";
        size_t length = strlen(str);
        printf("字符串 \"%s\" 的长度是 %zu\n", str, length);
        return 0;
    }

2. strcpy

  • 功能:将源字符串复制到目标字符串,包含字符串结束符 '\0'。需要确保目标字符串有足够的空间来存储源字符串。
  • 原型char *strcpy(char *dest, const char *src);
  • 返回值:返回指向目标字符串 dest 的指针。
  • 示例代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char src[] = "Example";
        char dest[20];
        strcpy(dest, src);
        printf("复制后的字符串是: %s\n", dest);
        return 0;
    }

    3. strcat

  • 功能:把源字符串追加到目标字符串的末尾,覆盖目标字符串原来的结束符 '\0',并在新字符串末尾添加结束符 '\0'。目标字符串要有足够的空间容纳追加后的内容。
  • 原型char *strcat(char *dest, const char *src);
  • 返回值:返回指向目标字符串 dest 的指针。
  • 示例代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char dest[20] = "Hello";
        char src[] = " World";
        strcat(dest, src);
        printf("追加后的字符串是: %s\n", dest);
        return 0;
    }

    4. strcmp

  • 功能:比较两个字符串的大小,通过比较字符串中对应位置字符的 ASCII 码值,逐个字符进行比较,直到遇到不同字符或字符串结束符 '\0'
  • 原型int strcmp(const char *s1, const char *s2);
  • 返回值
    • 若 s1 小于 s2,返回一个负整数。
    • 若 s1 等于 s2,返回 0。
    • 若 s1 大于 s2,返回一个正整数。
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    int result = strcmp(str1, str2);
    if (result < 0) {
        printf("\"%s\" 小于 \"%s\"\n", str1, str2);
    } else if (result == 0) {
        printf("\"%s\" 等于 \"%s\"\n", str1, str2);
    } else {
        printf("\"%s\" 大于 \"%s\"\n", str1, str2);
    }
    return 0;
}

5. strncpy

  • 功能:从源字符串复制最多 n 个字符到目标字符串。若源字符串长度小于 n,用 '\0' 填充目标字符串至 n 个字符;若源字符串长度大于等于 n,不会自动添加结束符 '\0'
  • 原型char *strncpy(char *dest, const char *src, size_t n);
  • 返回值:返回指向目标字符串 dest 的指针。
  • 示例代码
    #include <stdio.h>
    #include <string.h>
    
    int main() {
        char src[] = "abcdef";
        char dest[5];
        strncpy(dest, src, 4);
        dest[4] = '\0';  // 手动添加结束符
        printf("复制后的字符串是: %s\n", dest);
        return 0;
    }

    6. strncat

  • 功能:将源字符串的最多 n 个字符追加到目标字符串末尾,追加完成后会在新字符串末尾添加结束符 '\0'。目标字符串要预留足够空间。
  • 原型char *strncat(char *dest, const char *src, size_t n);
  • 返回值:返回指向目标字符串 dest 的指针。
    • 示例代码
      #include <stdio.h>
      #include <string.h>
      
      int main() {
          char dest[20] = "Hello";
          char src[] = ", World!";
          strncat(dest, src, 3);
          printf("追加后的字符串是: %s\n", dest);
          return 0;
      }

      7. strncmp

    • 功能:比较两个字符串的前 n 个字符的大小,按字符的 ASCII 码值逐个字符比较。
    • 原型int strncmp(const char *s1, const char *s2, size_t n);
    • 返回值
      • 若前 n 个字符中 s1 小于 s2,返回一个负整数。
      • 若前 n 个字符中 s1 等于 s2,返回 0。
      • 若前 n 个字符中 s1 大于 s2,返回一个正整数。
    • 示例代码
      #include <stdio.h>
      #include <string.h>
      
      int main() {
          char str1[] = "apple";
          char str2[] = "apricot";
          int result = strncmp(str1, str2, 2);
          if (result < 0) {
              printf("前2个字符中,\"%s\" 小于 \"%s\"\n", str1, str2);
          } else if (result == 0) {
              printf("前2个字符中,\"%s\" 等于 \"%s\"\n", str1, str2);
          } else {
              printf("前2个字符中,\"%s\" 大于 \"%s\"\n", str1, str2);
          }
          return 0;
      }

      8. strstr

    • 功能:在主字符串中查找子字符串第一次出现的位置。
    • 原型char *strstr(const char *haystack, const char *needle);
    • 返回值:若找到子字符串,返回指向该子字符串在主字符串中首次出现位置的指针;若未找到,返回 NULL
    • 示例代码
      #include <stdio.h>
      #include <string.h>
      
      int main() {
          char haystack[] = "Hello, World!";
          char needle[] = "World";
          char *result = strstr(haystack, needle);
          if (result != NULL) {
              printf("找到子字符串 \"%s\",位置是 %ld\n", needle, result - haystack);
          } else {
              printf("未找到子字符串 \"%s\"\n", needle);
          }
          return 0;
      }

      9. strtok

    • 功能:将字符串按指定的分隔符分割成多个标记(token)。第一次调用时传入要分割的字符串,后续调用传入 NULL 以继续分割同一个字符串。
    • 原型char *strtok(char *str, const char *delim);
    • 返回值:返回指向下一个标记的指针;若没有更多标记,返回 NULL
    • 示例代码
      #include <stdio.h>
      #include <string.h>
      
      int main() {
          char str[] = "apple,banana,orange";
          char *token = strtok(str, ",");
          while (token != NULL) {
              printf("%s\n", token);
              token = strtok(NULL, ",");
          }
          return 0;
      }

      10. strerror

    • 功能:根据错误码返回对应的错误信息字符串。错误码通常是全局变量 errno 的值。
    • 原型char *strerror(int errnum);
    • 返回值:返回指向描述错误信息的字符串的指针。
    • 示例代码
      #include <stdio.h>
      #include <string.h>
      #include <errno.h>
      
      int main() {
          FILE *fp = fopen("nonexistent_file.txt", "r");
          if (fp == NULL) {
              printf("打开文件失败,错误信息: %s\n", strerror(errno));
          }
          return 0;
      }

      总结:

    • 使用风险和注意事项
    • 这些函数均是 C 语言标准库 <string.h>strerror 也可能涉及 <errno.h>) 提供的用于字符串处理的实用工具,下面从功能、使用风险和注意事项方面进行总结:

      功能

    • 缓冲区溢出strcpy 和 strcat 若目标缓冲区空间不足,会导致数据越界覆盖相邻内存,引发程序崩溃或安全漏洞。strncpy 和 strncat 虽可指定复制或追加长度,但使用 strncpy 时若不手动添加结束符,可能造成后续处理错误。
    • 空指针问题:使用这些函数时,传入空指针(NULL)可能导致程序崩溃。调用前需确保指针有效。
    • 线程安全strtok 函数不是线程安全的,因为它使用了静态变量来保存分割状态。若在多线程环境下使用,需使用线程安全版本(如 strtok_r)。

                             通过以上的深刻认识到你们是否可以模拟类似这些的函数嘞

                                                     欢迎大家可以一起探讨一下

相关文章:

  • 【Swift 算法实战】利用 KMP 算法高效求解最短回文串
  • scp工具
  • ES6新增的变量
  • (七)趣学设计模式 之 适配器模式!
  • 算法15--BFS
  • 动态链接库
  • Pretraining Language Models with Text-Attributed Heterogeneous Graphs
  • Kubernetes控制平面组件:API Server Node 授权机制 详解
  • 刷题记录08
  • 16、Python面试题解析:python中的浅拷贝和深拷贝
  • 《Effective Objective-C》阅读笔记(上)
  • 电机控制的空间矢量调制 (SVPWM)
  • openharmony5.0中hdf框架中实现驱动程序的动态加载和管理的技术细节分析
  • C++中tuple的用法
  • Spring Boot 中的日志管理
  • 数据库设计的优化建议
  • AcWing 299 裁剪序列
  • 6种MySQL高可用方案对比分析
  • C语言基本知识------指针(4)
  • springboot004网页时装购物系统(源码+数据库+文档)
  • 中国田径巡回赛西安站完赛:男子跳远石雨豪夺冠,女子跳高刘肼毅折桂
  • 国新办将就2025年4月份国民经济运行情况举行新闻发布会
  • 在古老的意大利科莫歌剧院,廖昌永唱响16首中国艺术歌曲
  • 男子不满和睦家医院手术效果还遇到了“冒牌医生”?院方回应
  • 巴方:印度上周导弹袭击造成至少40名平民死亡
  • 联合国秘书长欢迎中美经贸高层会谈成果