a string problem
I have been given a problem that I haven't solved yet. My program need to work like this:
Put some string: Hello World Hello World World World
output: 4
The program get str开发者_JAVA百科ing and sub-string, the sub-string need to be found in the string and count the most common sub-string in the string.
I wrote some code but without success..
int main()
{
char string[10];
int i=0,x=0;
char find[] = "hello";
gets(string);
while(string[i] != 0)
if(string[i] == find[i]))
x++;
printf("%d", x);
i++;
return 0;
}
I think you'd be better off using the string library calls like
char *strstr( const char *s1, const char *s2) this returns a pointer to the first instance of string s2 in s1. Returns a NULL pointer if s2 is not encountered in s1.
You can find a list of them here: http://www.edcc.edu/faculty/paul.bladek/c_string_functions.htm
You might look at the second answer to this question, which basically points out that the most common sub-string will be a one character string, in your case 'o'. It sounds like you might want words instead of strings, in which case just break your string up into words and count those.
Hii,
try it this way
1) Take 1 string, 1 string array and one count array
2) first scan the string. You must use fgets as gets is not safe and even LINUX/UNIX documentation recommends to avoid it due to buffer over flow problem.
3) break the string in to words and store each unique word in the string array.
4) now take one word from the string array and compare it with string and count the occurrence. you better use some lib function like strstr
5) then store corresponding count in the count array
6) in the end scan count array for maximum count which will give you the max count and corresponding word.
精彩评论