#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; }
时间: 2024-11-05 22:57:58