size_t strtok

本文介绍了C语言中字符串长度统计函数strlen()的实现原理及注意事项,并通过实例演示了如何使用C语言统计输入文本中特定单词的出现次数。

C语言字符串长度统计函数strlen()的实现原理

C标准库中有一个字符串长度统计函数strlen(),用来统计字符串的长度,它的实现与下面类似。
   
  1. #include <stdlib.h>
  2. size_t strlen( char *string )
  3. {
  4. int length = 0;
  5. // 依次访问字符串的内容,计算字符数,直至遇到NUL终止符
  6. while( *string++ != '\0' )
  7. length += 1;
  8.  
  9. return length;
  10. }
#include <stdlib.h>
size_t strlen( char *string )
{
    int length = 0;
    // 依次访问字符串的内容,计算字符数,直至遇到NUL终止符
    while( *string++ != '\0' )
        length += 1;

    return length;
}
两点注意:
  • size_t 为stddef.h中定义的数据类型,等价于 unsigned int,它的取值必须大于等于0。
  • while()循环条件中,*string++等价于*(string++)。string是指针变量,保存的是字符串的起始地址(第一个字符的地址),地址是一个整数,可以进行算术运算,加 1 后为下一个字符的地址。


在指针到达字符串末尾的NUL字节之前,while语句中*string++表达式的值一直为真。它同时增加指针的值,用于下一次测试。这个表达式甚至可以正确地处理空字符串。

如果这个函数调用时传递给它的是一个NULL指针,那么while语句中的间接访问将会失败。函数是不是应该在解引用指针前检查这个条件?从绝对安全的角度讲,应该如此。但是,这个函数并不负责创建字符串。如果它发现参数为NULL,它肯定发现了一个出现在程序其他地方的错误。 当指针创建时检查它是否有效是合乎逻辑的,因为这样只需检查一次。这个函数采用的就是这种方 法。如果函数失败是因为粗心大意的调用者懒得检查参数的有效性而引起的,那是他活该如此。

 

 

 

 

C语言统计输入的单词的个数

编写一个程序,对标准输入进行扫描,并对单词“the”出现的次数进行计数。进行比较时应该区分大小写,所以“The”和“THE”并不计算在内。你可以认为各单词由一个或多个空格字符分隔,而且输入行在长度上不会超过100个字符。 计数结果应该写到标准输出上。

声明—个长度为101个字节的缓冲区数组,用于保存100个字节的输入和NUL终止符。strtok 函数用于逐个提取单词。
    
  1. // 计算标准输入中单词“the”出现的次数。字母是区分大小写的,输入中的单词由一个或多次空白字符分隔。
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. char const whitespace[] = " \n\r\f\t\v";
  7. int main ()
  8. {
  9. char buffer[101];
  10. int count;
  11. char *word;
  12. count = 0;
  13. // 读入文本行,直到发现EOF
  14. while( gets(buffer) ) {
  15. // 从缓冲区逐个提取单词,直到缓冲区内不再有单词。
  16. for( word = strtok ( buffer, whitespace );
  17. word != NULL;
  18. word = strtok( NULL, whitespace )
  19. ){
  20. if( strcmp( word, "the" ) == 0 )
  21. count += 1;
  22. }
  23. }
  24. printf("%d\n", count);
  25. return EXIT_SUCCESS;
  26. }


 

S4 s4_g_INP_getInputValues(U1P* u1pp_a_values, U4* u4p_a_count) { U1 u1_t_INPUT_line[MAX_INPUT_LENGTH]; printf("ENTER VALUES (0-255, SPACE SEPARATED): "); fflush(stdout); if (fgets((char*)u1_t_INPUT_line, sizeof(u1_t_INPUT_line), stdin) == NULL) { return (S4)-1; // 输入读取失败 } size_t st_t_LEN = strlen((char*)u1_t_INPUT_line); if (st_t_LEN == (size_t)1 && u1_t_INPUT_line[0] == '\n') { return (S4)0; // 空行输入 } if (st_t_LEN > (size_t)0 && u1_t_INPUT_line[st_t_LEN - (size_t)1] == '\n') { u1_t_INPUT_line[st_t_LEN - (size_t)1] = '\0'; // 移除换行符 } U1 u1_t_TEMP_values[100]; U4 u4_t_validCount = 0; // 有效值计数器(局部变量) U1P u1p_t_TOKEN = strtok((char*)u1_t_INPUT_line, " \t"); while (u1p_t_TOKEN != NULL && u4_t_validCount < (U4)100) { U1 u1_t_isValid = 1; // 标记当前令牌是否有效 U1P u1p_ptr = u1p_t_TOKEN; // 检查字符有效性 while (*u1p_ptr) { if (!isdigit((U1)*u1p_ptr)) { printf("SKIPPING INVALID TOKEN '%s' (NON-DIGIT CHAR '%c')\n", u1p_t_TOKEN, *u1p_ptr); u1_t_isValid = 0; break; } u1p_ptr++; } // 检查数值范围 if (u1_t_isValid) { S4 s4_t_VAL = atoi((char*)u1p_t_TOKEN); if (s4_t_VAL < (S4)0 || s4_t_VAL > (S4)255) { printf("SKIPPING OUT-OF-RANGE TOKEN '%s' (VALUE %d)\n", u1p_t_TOKEN, s4_t_VAL); u1_t_isValid = 0; } else { u1_t_TEMP_values[u4_t_validCount++] = (U1)s4_t_VAL; } } u1p_t_TOKEN = strtok(NULL, " \t"); // 继续处理下一个令牌 } // 处理结果 *u4p_a_count = u4_t_validCount; if (u4_t_validCount == 0) { return (S4)0; // 无有效输入 } *u1pp_a_values = (U1P)malloc(u4_t_validCount * sizeof(U1)); if (*u1pp_a_values == NULL) { return (S4)-1; // 内存分配失败 } memcpy(*u1pp_a_values, u1_t_TEMP_values, u4_t_validCount * sizeof(U1)); return (S4)1; // 成功读取有效值 } 注释全改成英文,格式为/* */,且只能有一个return,return一个变量,给变量赋值
09-13
S4 s4_g_INP_getInputValues(U1P* u1pp_a_values, U4* u4p_a_count) { U1 u1_t_INPUT_line[MAX_INPUT_LENGTH]; printf("ENTER VALUES (0-255, SPACE SEPARATED): "); fflush(stdout); if (fgets((char*)u1_t_INPUT_line, sizeof(u1_t_INPUT_line), stdin) == NULL) { return (S4)-1; } size_t st_t_LEN = strlen((char*)u1_t_INPUT_line); if (st_t_LEN == (size_t)1 && u1_t_INPUT_line[0] == ‘\n’) { return (S4)0; } if (st_t_LEN > (size_t)0 && u1_t_INPUT_line[st_t_LEN - (size_t)1] == ‘\n’) { u1_t_INPUT_line[st_t_LEN - (size_t)1] = ‘\0’; } U1 u1_t_TEMP_values[100]; u4p_a_count = (U4)0; U1P u1p_t_TOKEN = strtok((char)u1_t_INPUT_line, " \t"); while (u1p_t_TOKEN != NULL && *u4p_a_count < (U4)100) { U1P u1p_ptr = u1p_t_TOKEN; while (*u1p_ptr) { if (!isdigit((U1)*u1p_ptr)) { printf(“INVALID CHAR ‘%c’ IN ‘%s’\n”, u1p_ptr, u1p_t_TOKEN); return (S4)-1; } u1p_ptr++; } S4 s4_t_VAL = atoi((char)u1p_t_TOKEN); if (s4_t_VAL < (S4)0 || s4_t_VAL > (S4)255) { printf(“VALUE %d OUT OF RANGE\n”, s4_t_VAL); return (S4)-1; } u1_t_TEMP_values[(*u4p_a_count)++] = (U1)s4_t_VAL; u1p_t_TOKEN = strtok(NULL, " \t"); } if (*u4p_a_count == (U4)0) { return (S4)0; } *u1pp_a_values = (U1P)malloc(*u4p_a_count * sizeof(U1)); if (*u1pp_a_values == NULL) { return (S4)-1; } memcpy(*u1pp_a_values, u1_t_TEMP_values, *u4p_a_count * sizeof(U1)); return (S4)1; } 如果有一个输入令牌超出范围或者是非法输入了一个字符应该是做范围检查提示该令牌超出范围或非法,跳过这个数之后,让用户继续运行,输入选择,而不是直接退出
09-13
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> #include "include/aip_common.h" #include "include/dynamic_array.h" #include "include/search_functions.h" #define BUFFER_SIZE 512 /*===================================================================================================================================*/ /* Function Name: v_s_main_print_int */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Prints an integer element from void pointer */ /* Arguments: VDP vdp_a_elem : Void pointer to integer element */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_print_int(VDP vdp_a_elem) { printf("%d", *(S4 *)vdp_a_elem); } /*===================================================================================================================================*/ /* Function Name: v_s_main_print_float */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Prints a float element from void pointer */ /* Arguments: VDP vdp_a_elem : Void pointer to float element */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_print_float(VDP vdp_a_elem) { printf("%.2f", *(float *)vdp_a_elem); } /*===================================================================================================================================*/ /* Function Name: v_s_main_print_char */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Prints a character element from void pointer */ /* Arguments: VDP vdp_a_elem : Void pointer to character element */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_print_char(VDP vdp_a_elem) { printf("'%c'", *(S1 *)vdp_a_elem); } /*===================================================================================================================================*/ /* Function Name: v_s_main_print_array */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Prints contents of dynamic array */ /* Arguments: const ST_DA_ARRAY *stp_a_arr : Pointer to dynamic array structure */ /* void (*vfp_a_print_element)(VDP) : Function pointer for element printing */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_print_array(const ST_DA_ARRAY *stp_a_arr, void (*vfp_a_print_element)(VDP)) { U4 u4_t_main_index; VDP vdp_t_main_elem; vdp_t_main_elem = NULL; printf("["); for (u4_t_main_index = U4_MIN; u4_t_main_index < stp_a_arr->u4_s_size; u4_t_main_index++) { vdp_t_main_elem = stp_a_arr->vdp_a_data + u4_t_main_index * stp_a_arr->u4_s_elem_size; vfp_a_print_element(vdp_t_main_elem); if (u4_t_main_index < stp_a_arr->u4_s_size - 1) { printf(", "); } } printf("]\n"); } /*===================================================================================================================================*/ /* Function Name: v_s_main_parse_int_array */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Parses integer input into dynamic array with validation */ /* Arguments: ST_DA_ARRAY *stp_a_arr : Pointer to dynamic array structure */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_parse_int_array(ST_DA_ARRAY *stp_a_arr) { S1 s1p_t_main_buffer[BUFFER_SIZE]; S1P s1p_t_main_token; U1 u1_t_main_valid_input = FALSE; S1P s1p_t_main_end; S4 s4_t_main_value; do { printf("Enter integers separated by spaces: "); if (fgets(s1p_t_main_buffer, BUFFER_SIZE, stdin) == NULL) { printf(" [!] Input error. Please try again.\n"); continue; } s1p_t_main_token = strtok(s1p_t_main_buffer, " "); u1_t_main_valid_input = FALSE; while (s1p_t_main_token != NULL) { s4_t_main_value = strtol(s1p_t_main_token, (char **)&s1p_t_main_end, 10); /* Validate integer input */ if (s1p_t_main_end == (S1P)s1p_t_main_token) { printf(" [!] Invalid integer: '%s'. Skipped.\n", s1p_t_main_token); } else if (*s1p_t_main_end != '\0' && *s1p_t_main_end != '\n') { printf(" [!] Trailing characters in '%s'. Using %d.\n", s1p_t_main_token, s4_t_main_value); } else if (s4_t_main_value > INT_MAX || s4_t_main_value < INT_MIN) { printf(" [!] Integer out of range: '%s'. Skipped.\n", s1p_t_main_token); } else { S4 s4_t_main_value = s4_t_main_value; v_g_da_push_back(stp_a_arr, &s4_t_main_value); u1_t_main_valid_input = TRUE; } s1p_t_main_token = strtok(NULL, " "); } if (!u1_t_main_valid_input) { printf(" [!] No valid integers entered. Please try again.\n"); } } while (!u1_t_main_valid_input); } /*===================================================================================================================================*/ /* Function Name: v_s_main_parse_float_array */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Parses float input into dynamic array with validation */ /* Arguments: ST_DA_ARRAY *stp_a_arr : Pointer to dynamic array structure */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_parse_float_array(ST_DA_ARRAY *stp_a_arr) { S1 s1p_t_main_buffer[BUFFER_SIZE]; U1P s1p_t_main_token; U1 u1_t_main_valid_input = FALSE; do { printf("Enter floating-point numbers separated by spaces: "); if (fgets(s1p_t_main_buffer, BUFFER_SIZE, stdin) == NULL) { printf(" [!] Input error. Please try again.\n"); continue; } s1p_t_main_token = strtok(s1p_t_main_buffer, " "); u1_t_main_valid_input = FALSE; while (s1p_t_main_token != NULL) { S1P s1p_t_main_end; float f_t_main_value = strtof(s1p_t_main_token, (char **)&s1p_t_main_end); /* 验证浮点数输入 */ if (s1p_t_main_end == (S1P)s1p_t_main_token) { printf(" [!] Invalid float: '%s'. Skipped.\n", s1p_t_main_token); } else if (*s1p_t_main_end != '\0' && *s1p_t_main_end != '\n') { printf(" [!] Trailing characters in '%s'. Using %.2f.\n", s1p_t_main_token, f_t_main_value); } else { v_g_da_push_back(stp_a_arr, &f_t_main_value); u1_t_main_valid_input = TRUE; } s1p_t_main_token = strtok(NULL, " "); } if (!u1_t_main_valid_input) { printf(" [!] No valid floats entered. Please try again.\n"); } } while (!u1_t_main_valid_input); } /*===================================================================================================================================*/ /* Function Name: v_s_main_parse_char_array */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Parses character input into dynamic array with validation */ /* Arguments: ST_DA_ARRAY *stp_a_arr : Pointer to dynamic array structure */ /* Return: void */ /*===================================================================================================================================*/ static void v_s_main_parse_char_array(ST_DA_ARRAY *stp_a_arr) { U1 s1p_t_main_buffer[BUFFER_SIZE]; U4 u4_t_main_index; U1 u1_t_main_valid_input = FALSE; do { printf("Enter characters without spaces: "); if (fgets((S1 *)s1p_t_main_buffer, BUFFER_SIZE, stdin) == NULL) { printf(" [!] Input error. Please try again.\n"); continue; } u1_t_main_valid_input = FALSE; for (u4_t_main_index = U4_MIN; u4_t_main_index < BUFFER_SIZE; u4_t_main_index++) { S1 s1_t_main_value = s1p_t_main_buffer[u4_t_main_index]; if (s1_t_main_value == '\n' || s1_t_main_value == '\0') { break; } if (s1_t_main_value != ' ') { // 排除空格 v_g_da_push_back(stp_a_arr, &s1_t_main_value); u1_t_main_valid_input = TRUE; } } if (!u1_t_main_valid_input) { printf(" [!] No valid characters entered. Please try again.\n"); } } while (!u1_t_main_valid_input); } /*===================================================================================================================================*/ /* Function Name: main */ /* --------------------------------------------------------------------------------------------------------------------------------- */ /* Description: Main program for dynamic array operations with enhanced robustness */ /* Arguments: void */ /* Return: S4 : Exit status */ /*===================================================================================================================================*/ S4 main(void) { S4 s4_t_main_choice = S4_MIN; U1 u1_t_main_exit_flag = FALSE; while (!u1_t_main_exit_flag) { printf("\n===== Dynamic Array Program =====\n"); printf("1. Integer Sorting and Binary Search\n"); printf("2. Float Sorting and Binary Search\n"); printf("3. Character Sorting and Binary Search\n"); printf("4. Exit Program\n"); printf("Please select an option (1-4): "); /* 增强菜单选择验证 */ if (scanf("%d", &s4_t_main_choice) != 1) { printf(" [!] Invalid input. Please enter a number.\n"); while (getchar() != '\n'); // 清除输入缓冲区 continue; } getchar(); // 消耗换行符 if (s4_t_main_choice == 4) { printf("Exiting program.\n"); u1_t_main_exit_flag = TRUE; continue; } if (s4_t_main_choice < 1 || s4_t_main_choice > 3) { printf(" [!] Invalid choice. Please select 1-4.\n"); continue; } ST_DA_ARRAY st_t_main_array; void (*vfp_t_main_print_element)(VDP) = NULL; S4 (*s4fp_t_main_compare)(const VDP, const VDP) = NULL; void (*vfp_t_main_parse_array)(ST_DA_ARRAY *) = NULL; U1 u1_t_main_found = FALSE; U1 s1p_t_main_buffer[BUFFER_SIZE]; switch (s4_t_main_choice) { case 1: v_g_da_init(&st_t_main_array, sizeof(S4)); vfp_t_main_print_element = v_s_main_print_int; s4fp_t_main_compare = s4_g_comp_int; vfp_t_main_parse_array = v_s_main_parse_int_array; break; case 2: v_g_da_init(&st_t_main_array, sizeof(float)); vfp_t_main_print_element = v_s_main_print_float; s4fp_t_main_compare = s4_g_comp_float; vfp_t_main_parse_array = v_s_main_parse_float_array; break; case 3: v_g_da_init(&st_t_main_array, sizeof(S1)); vfp_t_main_print_element = v_s_main_print_char; s4fp_t_main_compare = s4_g_comp_char; vfp_t_main_parse_array = v_s_main_parse_char_array; break; default: printf(" [!] Invalid choice. Please select a valid option.\n"); continue; } vfp_t_main_parse_array(&st_t_main_array); /* 空数组检查 */ if (st_t_main_array.u4_s_size == 0) { printf(" [!] Array is empty. Operation skipped.\n"); v_g_da_free(&st_t_main_array); continue; } printf("Original array: "); v_s_main_print_array(&st_t_main_array, vfp_t_main_print_element); printf("Sorting the array...\n"); v_g_da_bubble_sort(&st_t_main_array, s4fp_t_main_compare); printf("Sorted array: "); v_s_main_print_array(&st_t_main_array, vfp_t_main_print_element); /* 增强搜索值输入验证 */ U1 u1_t_main_valid_search = FALSE; do { printf("Enter the value to search: "); if (fgets((S1 *)s1p_t_main_buffer, BUFFER_SIZE, stdin) == NULL) { printf(" [!] Input error. Please try again.\n"); continue; } if (s4_t_main_choice == 1) { S1P s1p_t_main_end; U8 l_t_main_target = strtol(s1p_t_main_buffer, (char **)s1p_t_main_end, 10); if (s1p_t_main_end != (S1P)s1p_t_main_buffer && (*s1p_t_main_end == '\n' || *s1p_t_main_end == '\0')) { S4 s4_t_main_target = (S4)l_t_main_target; u1_t_main_found = u4_g_search_binary(&st_t_main_array, &s4_t_main_target, s4fp_t_main_compare); u1_t_main_valid_search = TRUE; } else { printf(" [!] Invalid integer. Please try again.\n"); } } else if (s4_t_main_choice == 2) { S1P s1p_t_main_end; float f_t_main_target = strtof(s1p_t_main_buffer, (char **)s1p_t_main_end); if (s1p_t_main_end != (S1P)s1p_t_main_buffer && (*s1p_t_main_end == '\n' || *s1p_t_main_end == '\0')) { u1_t_main_found = u4_g_search_binary(&st_t_main_array, &f_t_main_target, s4fp_t_main_compare); u1_t_main_valid_search = TRUE; } else { printf(" [!] Invalid float. Please try again.\n"); } } else if (s4_t_main_choice == 3) { if (strlen((S1 *)s1p_t_main_buffer) > 1 && s1p_t_main_buffer[1] != '\n') { printf(" [!] Only single character allowed. Using first character.\n"); } S1 s1_t_main_target = s1p_t_main_buffer[0]; u1_t_main_found = u4_g_search_binary(&st_t_main_array, &s1_t_main_target, s4fp_t_main_compare); u1_t_main_valid_search = TRUE; } } while (!u1_t_main_valid_search); if (u1_t_main_found) { printf("Value found in the array!\n"); } else { printf("Value not found in the array.\n"); } v_g_da_free(&st_t_main_array); } return 0; } ===== Dynamic Array Program ===== 1. Integer Sorting and Binary Search 2. Float Sorting and Binary Search 3. Character Sorting and Binary Search 4. Exit Program Please select an option (1-4): 1 Enter integers separated by spaces: 5 Original array: [0] Sorting the array... Sorted array: [0] Enter the value to search:
09-11
static void v_s_main_parse_int_array(ST_DA_ARRAY *stp_a_arr) { U1 u1_t_main_buffer[BUFFER_SIZE]; U1 *u1p_t_main_token; U1 u1_t_main_valid_input = FALSE; do { printf("Enter integers separated by spaces: "); if (fgets((S1 *)u1_t_main_buffer, BUFFER_SIZE, stdin) == NULL) { printf(" [!] Input error. Please try again.\n"); continue; } u1p_t_main_token = (U1 *)strtok((S1 *)u1_t_main_buffer, " "); u1_t_main_valid_input = FALSE; while (u1p_t_main_token != NULL) { char *u1p_t_main_end; long l_t_main_value = strtol((S1 *)u1p_t_main_token, &u1p_t_main_end, 10); /* 验证整数输入 */ if (u1p_t_main_end == u1p_t_main_token) { printf(" [!] Invalid integer: '%s'. Skipped.\n", u1p_t_main_token); } else if (*u1p_t_main_end != '\0' && *u1p_t_main_end != '\n') { printf(" [!] Trailing characters in '%s'. Using %ld.\n", u1p_t_main_token, l_t_main_value); } else if (l_t_main_value > INT_MAX || l_t_main_value < INT_MIN) { printf(" [!] Integer out of range: '%s'. Skipped.\n", u1p_t_main_token); } else { S4 s4_t_main_value = (S4)l_t_main_value; v_g_da_push_back(stp_a_arr, &s4_t_main_value); u1_t_main_valid_input = TRUE; } u1p_t_main_token = (U1 *)strtok(NULL, " "); } if (!u1_t_main_valid_input) { printf(" [!] No valid integers entered. Please try again.\n"); } } while (!u1_t_main_valid_input); } [{ "resource": "/c:/Users/siyuanll2102/Desktop/C#/T9/T9_2/main.c", "owner": "cpptools", "severity": 4, "message": "comparison of distinct pointer types lacks a cast [-Wcompare-distinct-pointer-types]", "source": "gcc", "startLineNumber": 101, "startColumn": 32, "endLineNumber": 101, "endColumn": 32 }]
09-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值