Say the sentence was "There's the spoons pass me one" I would like the program to print both "There's" as its the longest word with an " ' " and "spoons" because its the longest word.
I am trying to work it out using strings and arrays.
Im using Visuall Studio 2005 c++.
Also how can I get the program to tell me how many of 1 letter is in the whole sentence.
I need to create a C++ program which will analyze a sentence written in the code and print the longest words?
Here is a gift.
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
#include %26lt;vector%26gt;
using namespace std;
int findLetter(const string%26amp; str, const char letter)
{
size_t pos = 0;
int count = 0;
do
{
pos = str.find(letter, pos);
if (pos != string::npos)
{
count++;
pos++;
}
} while (pos != string::npos);
return(count);
}
void parseWords(vector%26lt;string%26gt; %26amp;a, string str)
{
size_t pos = 0;
size_t start = 0;
string tempStr;
do
{
pos = str.find(' ', start);
if (pos != string::npos)
{
tempStr = str.substr(start, pos - start);
pos++;
start = pos;
}
else
{
if (start != string::npos)
{
tempStr = str.substr(start);
}
}
a.push_back(tempStr);
} while (pos != string::npos);
}
int main(int argc, char *argv[])
{
const string sentence("There's the spoons pass me one");
char letter;
//find requested letter
cout %26lt;%26lt; "Enter letter to find in sentence: ";
cin %26gt;%26gt; letter;
cout %26lt;%26lt; letter %26lt;%26lt; " occurs: " %26lt;%26lt; findLetter(sentence, letter) %26lt;%26lt; " times." %26lt;%26lt; endl;
//load array of words in sentence
vector%26lt;string%26gt; array;
parseWords(array, sentence);
//find longest word
int largestSize = 0;
string largestStr;
vector%26lt;string%26gt;::iterator pos = array.begin();
vector%26lt;string%26gt;::iterator end = array.end();
for (; pos != end; ++pos)
{
if (pos-%26gt;length() %26gt; largestSize)
{
largestSize = pos-%26gt;length();
largestStr = *pos;
}
}
cout %26lt;%26lt; "Largest word was \"" %26lt;%26lt; largestStr %26lt;%26lt; "\" with a size of " %26lt;%26lt; largestSize %26lt;%26lt; endl;
}
Reply:the one letter of each is easy store the string in an array and go through it letter by letter until you reach the end, have a switch set up example
get the letter put in x
switch (x)
case (a) :
case (b) :
for the first part count letters until white space, store location thats longest somewhere, index through whole sentense if longer replace if not stay the same at the end have a pointer pointing to the beginning of the longest word and print it out or whatever
should get you started think correctly
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment