本文包含字符串包含问题(isSubstr)、字符串转化为整数(atoi)、统计词频问题(Wordcount)、字符串反转(Reverse)。字符串去除空格等
一:字符串包含问题(isSubstr)
思路:本程序采用最简单的方法;
1、遍历源字符串,当子字符串的首字符与遍历到的字符相同时,就遍历字符串。
2、遍历子字符串时,如果遇到不相等,跳出子循环,源字符串的位置++;
3、若子循环遍历的长度恰好等于子字符串,那么原串包含子串,返回true。

1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include "assert.h" 5 6 //时间复杂度为O(lensub*(lens-lensub+1)) 7 int isSub(const char *str, const char*strsub) 8 { 9 assert(str != NULL && strsub != NULL); 10 11 int lens =strlen(str); 12 int lensub = strlen( strsub); 13 //若原串的长度不及子串的长度,则直接返回 14 if( lens < lensub) 15 return 0; 16 17 int i,j ;//自增量 18 for( i= 0; i <=lens- lensub; ++i)//循环次数 19 { 20 for( j =0; j < lensub; ++j) 21 if( str[i+j] != strsub[j]) 22 break; 23 if( j == lensub) 24 return 1; 25 } 26 return 0; 27 } 28 29 //测试用例最好多考虑几种情况 30 int main(int argc, char const *argv[]) 31 { 32 char s[] = "helloworld"; 33 char sub[] = "wo"; 34 35 printf("%d ", isSub(s, sub)); 36 return 0; 37 }
二:字符串转化为整数(atoi)
思路:依次遍历字符串,主要的执行语句:sum = sum*10 +'ch'-'0'
注意:
0、判断传入的参数是否为空;
1、返回值的长度问题,本程序返回值用 long long类型;
2、字符串的第一个字符有可能是‘+’,‘-’,因此要判断正负值问题;
3、转换时,如果遇到非法字符,则直接返回0;

1 #include <stdio.h> 2 #include <iostream> 3 #include <string> 4 #include <limits> 5 using namespace std; 6 7 long long aToi(const char *str) 8 { 9 if(str == NULL) 10 return 0; 11 long long num = 0; 12 13 const char *digit = str; 14 int flag =0; //标记正负 15 if( *digit == '-') //首位元素值得情况 16 flag = 1; 17 else if( *digit == '+') 18 flag =0; 19 else if( *digit >='0' && *digit <='9') 20 num = *digit - '0'; 21 else 22 return 0; 23 digit ++; 24 25 while( *digit != '