常用的字符串处理模型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | #include <stdio.h> #include <string.h> #include <ctype.h> /*strstr_while字串模型*/ int Search_count( char *p, char *str) { int ncount = 0; if (NULL == p || NULL == str) { printf ( "func Search_count() err: %d (NULL == p || NULL = str)\n" , ncount); return -1; } else { while (p = strstr (p, str)) { ncount++; p += sizeof (str); if (*p == '\0' ) break ; } return ncount; } } /*两头堵字串模型1*/ int NoSpaceLen1( char *str, char *newStr) { int i = 0, j = strlen (str) - 1; int ncount = 0; if (NULL == str || NULL == newStr) { printf ( "func NoSpaceLen1() err:-1 (NULL == str)\n" ); return -1; } while ( isspace (str[i]) && str[i] != '\0' ) i++; while ( isspace (str[j]) && str[j] != '\0' ) j--; ncount = j - i + 1; strncpy (newStr, str+i, ncount); //将两头去除空格后的子串保存至newStr中 newStr[ncount] = '\0' ; //此处需要特别注意,不能忘记加字串结尾标志 return ncount; } /*两头堵字串模型2*/ //此函数需要将去除空格后的子串保存到原str中,所以要求其所指向的内存空间可以被修改才可以 int NoSpaceLen2( char *str) { int i = 0, j = strlen (str)-1; int ncount = 0; if (NULL == str) { printf ( "func NoSpaceLen2() err: -1 (NULL == str)!\n" ); return -1; } else { while ( isspace (str[i]) && str[i] != '\0' ) i++; while ( isspace (str[j]) && str[j] != '\0' ) j--; ncount = j - i + 1; strncpy (str, str+i, ncount); //将两头去除空格后的子串保存至原str中 str[ncount] = '\0' ; //此处需要特别注意,不能忘记加字串结尾标志 return ncount; } } /*字符串反转1*/ //此函数需要将反转的字串保存到原str中,所以要求其所指向的内存空间可以被修改才可以 int Inverse( char *str) { int len = strlen (str); char *p1, *p2; char temp; if (NULL == str) { printf ( "func Inverse() err: -1 (NULL == str)!\n" ); return -1; } else { p1 = str; p2 = str + len -1; while (p1 < p2) { temp = *p1; *p1 = *p2; *p2 = temp; p1++; p2--; } return 1; } } int main() { char *p = "54abcd12133abcd22abcd333333abcd" ; char *s = "" ; char *str = " sdfssf " ; char newStr[1024] = { 0 }; char s1[20] = " 99 ds " ; char s2[20] = " I love you ! " ; if (Search_count(p, s) != -1) printf ( "字符串%s中含有%d个字串%s!\n\n" , p, Search_count(p, s), s); if (NoSpaceLen1(str, newStr) != -1) printf ( "该字串去除前后空格后的字符数: ncount = %d 子串:%s\n\n" , NoSpaceLen1(str, newStr), newStr); if (NoSpaceLen2(s1) != -1) printf ( "该字串去除前后空格后的字符数: ncount = %d 字串:%s\n\n" , NoSpaceLen2(s1), s1); Inverse(s2); printf ( "%s\n%d\n" , s2); return 0; } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步