C语言,查找子字符串并统计个数
2014-07-08 12:10 kingshow 阅读(5714) 评论(0) 编辑 收藏 举报
一、C语言,在一个字符串中查找一个子字符串,并统计个数~
EX:
#include <stdio.h> #include <string.h> int find_string(char str[],char substr[]); int main() { /* char ch[10] = {"qweasd"}; int n = strlen(ch); int sn = sizeof(ch); printf("%d\n", n); printf("%d\n",sn); */ char ch1[] = "12"; char ch2[] = "323 12j34312j 434212435 412"; int sum = find_string(ch2,ch1); printf("%d\n",sum); return 0; } int find_string(char str[], char substr[]) { int count = 0,i,j,check; int len = strlen(str); int sublen = strlen(substr); for(i = 0; i < len; i++) { check = 1; for(j = 0; j + i < len && j < sublen; j++) { if(str[i+j] != substr[j]) { check = 0; break; } } if(check == 1) { count++; i = i + sublen; } } return count; }
二、从二维数组中查找指定长度的回文字符串
#include <stdio.h> #include <string.h> int main() { char ch[8][8] = {{'z','x','x','e','z','c','x','z'},{'q','w','p','q','e','w','r','e'},{'q','w','e','e','w','a','q','w'},{'q','e','w','q','e','r','r','e'}, {'q','w','e','e','w','q','e','r'},{'q','w','w','q','e','r','r','e'},{'q','w','e','e','w','q','e','r'},{'q','w','w','q','e','r','r','e'}}; int i,j,k,len,check = 0,count = 0; int length = 4; //查找长度 for(i=0; i<8; i++) { for(j=0; j <= 8-length; j++) { /* check = 0; for(k=0; k<length/2; k++) { if(ch[i][j+k] != ch[i][j+length-k-1]) { check = 1; break; } } if(check == 0) { count++; }*/ len = 0; while((ch[i][j+len] == ch[i][j+length-len-1]) && j+len < 8) { if(len == length/2) { count++; break; } len++; } } } printf("count:%d\n",count); return 0; }