max and min word in string

How me find max and min word in the string?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  #include <iostream>
#include<cstring>
#include<iomanip>
using namespace std;
int count=0;
int wordsstr(const char*pstr)    //number words
{
	 while (*pstr!='\0')
	 {
		 if(*pstr==' ')
		 {
			 count++;
		 }
		 pstr++;
	 }
	 return count+1;
}

int main()
{
	 const int len=20;
	 char str1[len];
	 char str2[len];

	 cout<<"enter str1"<<endl;
	 cin.getline(str1,len);
	 cout<<str1<<endl;
	 cout<<"enter str2"<<endl;
	 cin.getline(str2,len);
	 cout<<str2<<endl;

	 cout<<wordsstr(str1)<<endl;
	 cout<<wordsstr(str2)<<endl;
return 0;
}
It looks like you've copied this code from somewhere. Have you any idea what it does or how it works?

I'll add comments to the search function to help, but it's difficult to help if we don't know how much you know.
1
2
3
4
5
6
7
8
9
10
11
12
13
int wordsstr(const char*pstr)
{
	int count = 0;		// I added this, counter starts off at zero
	while (*pstr!='\0')	// while we've not hit the end of the string
	{
		if (*pstr==' ')	// check if the character is a space
		{
			count++;// increment the counter
		}
		pstr++;		// move to the next character in the string
	}
	return count+1;		// return one more than count
}
Last edited on
this example i'm decided on my school
this function couted words in the string
this function couted words in the string

No it didn't. It counted the number of spaces. If there were the same number of words as spaces, then that's just lucky. If you pass "", it will return 1. If you pass " " (5 spaces) it will return 6.

To count words, you need to count the transitions from non-letters to letters.
Topic archived. No new replies allowed.