C:一个字符数组里面解析出多个字符串
一个字符数组里面存放了多个字符串,每个字符串以 ‘\0’。要求把这些有效字符串筛选出来并输出。
扩展:'\0\0' 表示字符串结束。V2 方法就是实现的这个扩展功能。
#include <stdio.h> #include <string.h> #include <malloc.h> void printSzNameList(char szNameList[], int length){ printf("\r\n-------------- start printStringList------------------\r\n"); char temp[256] = {0}; // 假设每个字符串都不会超过127个字符(留一个位置给'\0') const char *start = szNameList; // 指向当前正在处理的字符串的起始位置 // 遍历整个数组直到遇到结尾或超出长度 while (start < szNameList + length) { // 找到当前字符串的结尾('\0') const char *end = strchr(start, '\0'); // 检查是否找到了结尾且没有超出数组范围 if (end == NULL || (size_t)(end - szNameList) >= length) { // 如果没有找到结尾或超出了数组范围,则停止 break; } // 使用memcpy将字符串复制到临时变量中(包括结尾的'\0') // 注意:这里我们不需要+1来包含'\0',因为strchr已经返回了指向'\0'的指针 // 但为了安全起见,我们仍然使用end - start来计算长度(实际上这包括了'\0') memcpy(temp, start, end - start); // 输出字符串 int charLen = strlen(temp); if(charLen>0){ printf("%s\n", temp); } // 将临时变量清零(实际上这一步是多余的,因为temp在每次循环开始时都会被重新使用) // 但为了符合您的要求,我们还是执行它 memset(temp, 0, sizeof(temp)); // 更新start指针到下一个字符串的开始位置 start = end + 1; } printf("\r\n------------- end printStringList------------------\r\n"); } void printSzNameListV2(char* ptr){ printf("\r\n-------------- start printStringListV2------------------\r\n"); while(ptr && ptr[0]) { printf("%s\n", ptr); ptr += (strlen(ptr) + 1); } printf("\r\n------------- end printStringListV2------------------\r\n"); } void test1(){ printf("========== test1 ============= "); char szNameList1[128] = "a11\0a22\0a33\0abcde\0\0\0\0abcdef\0\0"; //char szNameList2[128] = "a11\0a22\0a33\0abcde\0\0\0\0abcdef\0\0"; printSzNameList(szNameList1, sizeof(szNameList1)); printSzNameListV2(szNameList1); } void test2(){ printf("========== test2 ============= "); char szNameList1[128] = "a11\0a22\0a33\0abcde\0\0\0\0abcdef\0\0ghijklmn"; //char szNameList2[128] = "a11\0a22\0a33\0abcde\0\0\0\0abcdef\0\0"; printSzNameList(szNameList1, sizeof(szNameList1)); printSzNameListV2(szNameList1); } void main(){ printf("hello c 20240816\n"); test1(); test2(); } // gcc c_demo1.c -std=c11 -o demo1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?