How to find the shortest word in the string C++ - c++

I need a help.
I have a function which print Longest Word in sentence.
But how to display shortest word?
string text = "My name is Bob";
void LongestWord(string text)
{
string tmpWord = "";
string maxWord = "";
for(int i=0; i < text.length(); i++)
{
/// If founded space, rewrite word
if(text[i] != ' ')
tmpWord += text[i];
else
tmpWord = "";
/// All the time check word length and if tmpWord > maxWord => Rewrite.
if(tmpWord.length() > maxWord.length())
maxWord=tmpWord;
}
cout << "Longest Word: " << maxWord << endl;
cout << "Word Length: " << maxWord.length() << endl;
}

The suggestion given in the comment section will work, it's just a matter of rearranging your control structures to make it work. i.e
for(int i=0; i < text.length(); i++)
{
/// If founded space, rewrite word
if(text[i] != ' ')
tmpWord += text[i];
else
{
if(minWord.length()==0)//this only happens once
minWord=tmpWord;//for the first word,you need to assign minWord so you have something to compare to
if(tmpWord.length() < minWord.length() )//move this block here
minWord=tmpWord;
tmpWord = "";
}
}
I might add, you can check for a word much easily if you used istringstream with the extraction operator>>. Something like:
#include <sstream>
....
string text="my name is bob";
string tmpWord = "";
string minWord = "";
istringstream ss(text);//defines the input string stream and sets text in the input stream buffer
while(ss.peek()!=EOF)//until the end of the stream
{
ss>>tmpWord;//read a word up to a space
if(minWord.length()==0)//this only happens once
minWord=tmpWord;
if(tmpWord.length() < minWord.length() )
minWord=tmpWord;
}

void ShortestWord(std::string const& text)
{
std::stringstream ss(text);
std::vector<std::string> v(std::istream_iterator<std::string>(ss), {});
auto min = std::min_element(v.begin(), v.end(),
[] (auto& lhs, auto& rhs) { return lhs.size() < rhs.size(); });
auto p = std::make_pair(*min, min->size());
std::cout << "Shortest Word: \"" << p.first << "\"\n";
std::cout << "Word Length: " << p.second << '\n';
}

void ShortestWord(string text)
{
string tmpWord = "";
// The upper bound of answer is text
string minWord = text;
for(int i=0; i < (int)text.length(); i++)
{
/// If founded space, rewrite word
if(text[i] != ' ')
{
tmpWord += text[i];
}
else
{
// We got a new word, try to update answer
if(tmpWord.length() < minWord.length())
minWord=tmpWord;
tmpWord = "";
}
}
// Check the last word
if(tmpWord != "")
{
if(tmpWord.length() < minWord.length())
minWord=tmpWord;
}
cout << "Shortest Word: " << minWord << endl;
cout << "Word Length: " << minWord.length() << endl;
}

If we want to get both min value and max value, the initialize values should be opposites to each of them.
Actually, that should be the max-limit string of 'text'.
In the development of the business application, this is common sense, but some programers may hate the way of this.
string minWord = text; // MAX_SIZE
string maxWord = "";
for(int i = 0; i < text.length(); i++)
{
/// If founded space, rewrite word
if(text[i] != ' ')
tmpWord += text[i];
if(text[i] == ' ' || i == text.length()) {
/// All the time check word length and if tmpWord > maxWord => Rewrite.
if(tmpWord.length() > maxWord.length())
maxWord = tmpWord;
if(tmpWord.length() < minWord.length())
minWord = tmpWord;
tmpWord = "";
}
}

Related

Program to reverse words of string except corner words

Output showing me only the first letter of string
//program to reverse all words except corner words
#include <bits/stdc++.h>
using namespace std;
void printReverse(string str)
{
//print first word
int i = 0;
for (i = 0; i < str.length() && str[i] != ' '; i++)
cout << str[i];
//print middle word
string word = "";
for (i = 0; i < str.length(); i++)
{
if (str[i] != ' ')
word += str[i];
else
{
reverse(word.begin(), word.end());
cout << word << " ";
word = "";
}
}
//print last word
cout << word << " ";
}
int main()
{
string str;
cout << "Enter the string: ";
cin >> str;
printReverse(str);
return 0;
}
Program to reverse all words except corner words. I'm not able to recognize what's wrong. It showed me only the first word of the string and the rest part of the code is working. Please help me.
public class HelloWorld {
public static void main(String[] args) {
String str = "Reverse string except corner";
int left = 0, right = 0;
int i = 0;
for(i = 0; i < str.length() && str.charAt(i) != ' '; i++)
{
System.out.print(str.charAt(i)); // Printing the first word
}
left = i;
String last = " ";
for(int j = str.length()-1; j >=0 && str.charAt(j) != ' '; j--)
{
last = str.charAt(j) + last; // Storing the last word
right = j;
}
String mid = str.substring(left, right); // Getting the middle words
for(int k = mid.length()-1; k >= 0; k--)
{
System.out.print(mid.charAt(k));
}
System.out.println(last);
}
}
Output

How to parse a string and ignore whitespace?

int line = 0;
string teststring = " ";
string stringarray[100];
while (codeFile.good())
{
getline(codeFile, teststring, ' ');
if(teststring!="" && teststring[0]!='\n' && teststring[0] != 9 && teststring[0] != 10 && teststring[0] != 32 && teststring[0]!=' '
&& teststring!=" " && teststring!=" ")
{
stringarray[line]=teststring; // still stores whitespace :(
cout << stringarray[line] << endl;
line++;
}
}
Hello, I am going through a text file and trying to store each string inside an element of an array but, am having problems with elements storing completely white space.
I have just solve a similar problem, how about this code:
while (codeFile.good())
{
getline(codeFile, teststring);
for(size_t idx = 0; idx < teststring.size(); i++) {
size_t start = idx;
while (teststring[i] != ' ') {
idx++;
}
stringarray[line] = teststring.substr(start, idx - start);
cout << stringarray[line] << endl;
line++;
}
}
Ignoring all the white spaces is exactly what operator>> does.
Your snippet can be rewritten as:
// ...
std::string word;
std::vector<std::string> words;
while ( codeFile >> word )
{
if ( word.empty() ) continue;
std::cout << word << '\n';
words.push_back(std::move(word));
}

How to deal with space input comparing word inverse C++

We are taking user input and reversing it in the background and asking the user what is the reverse. Then we compare realreverse and userreverse and say that it's correct or how many mistakes were made. Also we are counting sentences with using dots, and the user should end his input with #.
For example:
hi. how are you doing. #
or
hi bro how are u.
im good. #
The problem is my program is only working if the input doesn't contain any spaces.
hihowareyoudoing. thanksimfinebro #
If the input is like that, it's working.
it works
hihowareyoudoing.
thanksimfinebro. #
This 2 column also working
code:
(program shows correct inverse for testing)
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
while (cin >> input && input != "#") {
result += input + " ";
}
int sentnumber = findsnumber(result);
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
while (cin >> reverse && reverse != "#"){
reverseson += reverse + "";
}
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
cin.ignore();
cin.get();
}
cin does not support input string with spaces. So, to input a string containing spaces you need to use getline()The correct syntax is std::getline(std::cin, input);
Edited Your Code!
#include <iostream>
#include <string>
using namespace std;
void Comparison(string reverseReal, string reverseUser) {
int wrongCount = 0;
if (reverseReal.length() != reverseUser.length()) {
cout << "These strings are not comparable." << endl;
}
else {
for (int i = 0; i < reverseReal.length(); i++) {
if (reverseReal.substr(i, 1) != reverseUser.substr(i, 1)) {
wrongCount++;
}
}
cout << "Number of mistakes: " << wrongCount << endl;
if (wrongCount == 0){
cout << "gj correct reverse" << endl;
}
}
}
string getReverse(string sentence) {
string reverseResult = "";
for (int i = sentence.length() - 1; i >= 0; i--) {
reverseResult += sentence.substr(i, 1);
}
return reverseResult;
}
int findsnumber(string snumber)
{
unsigned int sentences = 0, index = 0, length;
string searchPattern = ".";
length = snumber.length();
while (index < length)
{
index = snumber.find(searchPattern, index);
if (index != string::npos)
{
index += searchPattern.length();
sentences++;
}
}
return sentences;
}
// Gets the string until it finds a dot in it
string getOneSentence(string sentence) {
while (sentence.find(".") != string::npos) {
int dotFinder = 0;
string sub = "";
dotFinder = sentence.find(".");
sub = sentence.substr(0, dotFinder);
return sub;
}
return "";
}
int main() {
//char input = '\0';
string input = "";
string result = "";
string reverseReal = "";
int i = 1;
cout << "Welcome to my cancer c++ programme." << endl;
cout << "Enter the paragraph with # at the end to end it:" << endl;
getline(cin, input,'#');
result = input;
int sentnumber = findsnumber(result);
cin.clear();
cout << "Number of sentences in the given string " << sentnumber << endl;
while (result.find(".") != string::npos) {
string sub = "";
string subReverse = "";
string reverse = "";
string reverseson = "";
cout << i << "/" << sentnumber << endl;
sub = getOneSentence(result);
subReverse = getReverse(sub);
cout << "reverse of the sub " << subReverse << endl;
cout << "Sentence " << i << " : " << sub << endl;
cout << "Enter the reverse of your sentence" << endl;
cin.clear();
cin.ignore();
getline(cin,reverse,'#');
reverse.erase(reverse.end() - 1, reverse.end());
reverseson = reverse;
Comparison(subReverse, reverseson);
result = result.substr(result.find(".") + 2, result.length());
i++;
}
system("pause");
}

How to loop through multiple condition IF statement in C++

I am a newbie in programming and I wrote a piece of code that works, but I am interested in making it scalable.
The following code checks if a single word from a vector list matches with any of the words in another vector list.
if (words[i] != dislike[0] && words[i] != dislike[1] && words[i] != dislike[2] && words[i] != dislike[3]) //check for disliked words
cout << words[i] << '\n';
As visibile, the code does the job by iterating word by word, so if I were to change the nubmer of words in my second vector list, I will need to add it to the IF statement.
Is there a more optimal solution? I have been trying to figure this out for hours, however I had no luck.
Thanks.
P.S. Below is my full code.
int main()
{
// words we dislike
vector<string>dislike = { "broccoli", "coke", "potatoes", "water" };
//take input from user
vector<string> words;
for (string temp; cin >> temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
//give output
cout << "Number of words: " << words.size() << '\n';
//sort(words); // DONT sort the words
for (int i = 0; i<words.size(); ++i) //go through your words vector
{
if (i == 0 || words[i - 1] != words[i])//remove repeating words
{
if (words[i] != dislike[0] && words[i] != dislike[1] && words[i] != dislike[2] && words[i] != dislike[3]) //check for dislike
cout << words[i] << '\n';
else
cout << "BlEEP!\n"; //print if word is disliked*/
}
}
return 0;
}
What about this?
Adding another loop for that iterates throught all the dislike vector.
int main()
{
// words we dislike
vector<string>dislike = { "broccoli", "coke", "potatoes", "water" };
//take input from user
vector<string> words;
for (string temp; cin >> temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
//give output
cout << "Number of words: " << words.size() << '\n';
//sort(words); // DONT sort the words
for (int i = 0; i<words.size(); ++i) //go through your words vector
{
if (i == 0 || words[i - 1] != words[i])//remove repeating words
{
for(int j=0;j<dislike.size();j++)
{
int count = 0;
if (words[i] != dislike[j])count++;
if(count == dislike.size())cout << words[i] << '\n'; //check for dislike
else
cout << "BlEEP!\n"; //print if word is disliked*/
}
}
}
return 0;
}

Random characters popping up

When I debug my program, it outputs a random stream of characters when outputting the asterisked line.
int main ()
{
string inputPuzzle;
cout << "Enter a word or set of words: ";
getline(cin, inputPuzzle);
char* puzzle = new char[inputPuzzle.size()+1];
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
int strikes = 0;
char userInput;
char* userSoln = new char[inputPuzzle.size()];
for (int i = 0; i < inputPuzzle.size(); i++)
{
userSoln[i] = '-';
if (puzzle[i] == ' ')
{
userSoln[i] = ' ';
}
}
bool solved = false;
int numberOfLetters;
for (;;)
{
numberOfLetters = 0;
cin >> userInput;
for (int i = 0; i < inputPuzzle.size(); i++)
{
if (userInput == puzzle[i])
{
numberOfLetters++;
userSoln[i] = puzzle[i];
}
}
if (numberOfLetters == 0)
{
cout << "There are no " << userInput << "'s\n" ;
strikes++;
}
else
{
cout << "There are " << numberOfLetters << " " << userInput << "'s\n";
}
if (userSoln == puzzle)
{
break;
}
if (strikes == 10)
{
break;
}
**cout << "PUZZLE: " << userSoln << "\n";**
cout << "NUMBER OF STRIKES: " << strikes << "\n";
}
if (strikes == 10)
{
cout << "Sorry, but you lost. The puzzle was: " << puzzle;
}
else
{
cout << "Congratulations, you've solved the puzzle!!! YOU WIN!!!!!";
}
}
I've tried clearing cin buffers, but nothing doing. I have all the necessary include files (string and iostream) too, so that isn't the issue, and i have the namespace std above the main method.
This isn't a valid character constant.
puzzle[inputPuzzle.size()+1] = '';
If you intended a terminating character, it should be
puzzle[inputPuzzle.size()+1] = '\0';
or just
puzzle[inputPuzzle.size()+1] = 0;
or you could replace both these lines
memcpy(puzzle, inputPuzzle.c_str(), inputPuzzle.size()+1);
puzzle[inputPuzzle.size()+1] = '';
with strcpy
strcpy(puzzle, inputPuzzle.c_str());
Edit:
You also need to put a terminating character at the end of userSoln before printing it.
userSoln[ inputPuzzle.size() ] = '\0';
puzzle[inputPuzzle.size()+1] = '';
should be
puzzle[inputPuzzle.size()+1] = '\0';
you were trying to add the null terminator to the end of the string to signify the end, but '' is not quite it.