write a complete c++ program that finds and show the number of occurrences in given string?
string is taken from user.
1
Expert's answer
2013-07-22T12:00:46-0400
#include <iostream> #define lim 256 using namespace std; char s1[lim]; char s2[lim]; char c; int strlen(char s[]) { int i = 0; while (s[i] != ' ') ++i; return i; } int numb_occurrences(char s_1[], char s_2[]) { int n_o = 0; int n_c=0; int i = 0; int j = 0; while(s_1[i] != ' ') { if (s_2[j]!=s_1[i]) { j = 0; n_c = 0; } if (s_2[j] == s_1[i]) { ++n_c; if (strlen(&s_2[0]) > n_c) j++; if (strlen(&s_2[0]) == n_c) n_o++; } ++i; } return n_o; } int main() { do { int i=0; cout<<"Enter the string "<<endl; for ( i=0; i<lim && (c = getchar())!= EOF && c!=' ';++i) s1[i]=c; s1[i]=' '; cout<<endl; cout<<"Enter a search string (must not be longer than the first)"<<endl; i=0; for ( i=0; i<lim && (c = getchar())!= EOF && c!=' ';++i) s2[i]=c; s2[i]=' '; } while (strlen(&s2[0]) > strlen(&s1[0])); cout<<"The number of occurrences of the string 2 in line 1 : "<<numb_occurrences(&s1[0], &s2[0])<<endl; system("pause"); return 0; }
Comments
Leave a comment