i am trying to display the longest word in a sentence. first i am trying to display the length of the longest word but it is not displaying the correct length i.e, i have a string s = "This is string" so it displays the length of a longest word as "4" but here it is "6". and secondly i want to display that word as well.
1. If s[i] is not a space, workingWord += s[i]
2 If s[i] is a space or at the end of the string, and workingWord size > maxWord size, let maxWord=workingWord and reset workingWord.
3. if s[i] is a space and workingWord size < maxWord size, then just reset workingWord.
If you don't check for punctuation as well as space, it will be included as part of the word.
You are not setting workingWord back to "" after you make longWord=workingWord.
Your for loop will go farther than it needs to: the last usable character in your string is s[(s.size-1)].
In other words, your string array starts from 0 not 1--the [i] in s[i] is an address, and s.length() is a count.
For such a small program, you're better off using as few variables as possible. For example workingLen is the same as workingWord.length(), that way you're keeping it simple.
If you weren't almost finished, I'd ask you t o try to use only 4 variables:
string s,
string workingWord
string longWord
unsigned int i
workingWord="" should go together with counter=0. If you have detected a space it's time to start a new working word.
And you shouldn't use elseif. What if s[i] is not a space but it is the end of the string? Just use if
You should also check if it is the end of the string, if (s[i] =' ' || i=(len-1)) will check for the end of a word and the end of the string (punctuation included in the word).
#include <iostream>
#include <string>
usingnamespace std;
string input="This is string";
string workingWord=""; //working string
string maxWord=""; //biggest word
unsigned i=0; //string iterator
int main()
{
for (i=0; i < input.size(); i++)
{
//If it's not a space, add it to the word, if it is, reset workingWord.
if (input[i] != ' ') workingWord += input[i]; else workingWord="";
//if workingword > maxWord , you have a new maxWord.
if (workingWord.size() > maxWord.size()) maxWord=workingWord;
}
cout << "\n" << maxWord << "\t" << maxWord.size();
return 0;
}