Find a word in a sentence c++ - c++

This code should say if a word is present in a sentence or not. When I insert the sentence and the word where I declare the strings(for exemple: string s = "the cat is on the table" string p = "table" the program says that the word is in the sentence) the code works but, with the getline, the for cycle never begin and it always says that the word isn't in the sentence.
Please help I dont know what to do
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}

after taking the input strings then use length() to find the length, otherwise you are not taking the actual size of the strings.
getline(cin, s);
getline(cin, p);
int sl = s.length();
int pl = p.length();
For splitting the words after taking the input string by getline() you can use stringstream which is a builtin c++ function, like :
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
while(ss >> word){
// your desired strings are in `word` one by one
cout << word << "\n";
}
}
Another thing is that you can declare the strings like string s, p, word;

Related

c++ problem with reverse and count string

I'm just learning c++. I have a problem with my program. I have to write a program which reverse string and count amount word in the string. My program doesn't return amount words and reverse only last word in string. I totally don't know how to correct it. :D
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
void countString(string strg)
{
int word = 1;
for(int j = 0; strg[j] != '\0'; j++)
{
if (strg[j] == ' ')
{
word++;
}
}
}
int main(void)
{
string inputString;
cout << "Give a string: ";
cin >> inputString;
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
countString(inputString);
return 0;
}
If you want to read multiple words then you must use getline as >> reads only a single word.
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
To return something from a function you must 1) specify the return type and 2) use a return statement to return a value and 3) do something with that return value in the calling function
Step 1
int countString(string strg) // here we say countString returns an integer
{
...
}
Step 2
int countString(string strg)
{
...
return words; // here we say the value we want to return
}
Step 3
// here we output the value returned from the function
cout << "\nCounts words in a string: " << countString(inputString) << "\n";
Knowing how to write functions that return values is absolutely fundamental C++. You should practise this. See if you can do the same with your reverseString function, instead of printing a string make it return a string.
There are some mistake in your code.In countString() function you return nothing.So it does not print anything.If you take input as a string include a space character,please use getline(cin, inputString).Here the code for you:
#include <iostream>
using namespace std;
void reverseString(string str)
{
for (int i=str.length()-1; i>=0; i--)
{
cout << str[i];
}
}
int countString(string strg)
{
int word = 0;
for(int j = 0; strg[j] != '\0'; j++)
{
word++;
}
return word;
}
int main(void)
{
string inputString;
cout << "Give a string: ";
getline(cin, inputString);
cout << "Reverse string: ";
reverseString(inputString);
cout << "\nCounts words in a string: ";
cout<<countString(inputString)<<endl;
return 0;
}

Find words beginning with 's' using set/multiset

The issue I'm having with this code stems from the last block of code for the get_words_beginning_s function.
/*
Name: xx
Date: xx
Purpose:Read text from file, count number of words, unique words, word frequency, & number of words that begin with letter 's'
*/
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
multiset<string> display_and_load_words(string filename);
set<string> get_unique_words(multiset<string>& words);
set<string> get_words_beginning_s(multiset<string>& words);
int main() {
cout << "The Word Counter program\n\n";
string filename = "dickens.txt";
cout << "FILE TEXT: ";
//display_text(filename);
auto words = display_and_load_words(filename);
cout << "WORD COUNT: " << words.size() << endl << endl;
auto unique_words = get_unique_words(words);
auto words_beginning_s = get_words_beginning_s(words);
cout << unique_words.size() << " UNIQUE WORDS: ";
for (string word : unique_words) {
cout << word << ' ';
}
cout << endl << endl;
cout << "COUNT PER WORD: ";
for (string word : unique_words) {
cout << word << '=' << words.count(word) << ' ';
}
cout << endl << endl;
cout << "WORDS THAT BEGIN WITH 'S': ";
for (string word : words_beginning_s) {
cout << word << ' ';
}
cout << endl << endl;
}
multiset<string> display_and_load_words(string filename) {
multiset<string> words;
ifstream infile(filename);
if (infile) {
string word;
while (infile >> word) {
cout << word << ' ';
string new_word = "";
for (char c : word) {
if (c == '.' || c == ',') {
continue; // remove punctuation
}
else if (isupper(c)) {
new_word += tolower(c); // convert to lowercase
}
else {
new_word += c;
}
}
words.insert(new_word); // add word
}
cout << endl << endl;
infile.close();
}
return words;
}
set<string> get_unique_words(multiset<string>& words) {
set<string> unique_words;
for (string word : words) {
auto search = unique_words.find(word);
if (search == unique_words.end()) {
unique_words.insert(word);
}
}
return unique_words;
}
set<string> get_words_beginning_s(multiset<string>& words) {
set<string> words_beginning_s;
for (string word : words) {
auto search = words_beginning_s.find(word);
if (search == words_beginning_s.end()) {
for (int i = 0; i < words_beginning_s.size(); ++i) {
if (words_beginning_s[0] == 's') {
words_beginning_s.insert(word);
}
}
}
}
return words_beginning_s;
}
If working with set/multiset, how does one compare positional values within each separate word itself, rather the entire words? Example string in text file - "John goes to the store": Whereas normally a simple for loop can be used with the initial position to compare values and count number of times it appears (something like)-
for (int i = 0; i < words_beginning_s.length(); ++i) {
if (words_beginning_s[0] == 's') {
++s_word;
}
This does not work when using set/multiset. Pretty new to this, so sorry if this question seems dumb.
You can use the multisets member function lower_bound to get iterators to a range and then create a set from that range.
Example:
#include <iostream>
#include <set>
#include <string>
std::set<std::string> get_words_beginning_s(const std::multiset<std::string>& words) {
// create a set from the iterators you get from lower_bound("s") and lower_bound("t"):
return {words.lower_bound("s"), words.lower_bound("t")};
}
int main() {
std::multiset<std::string> words{
"foo", "slayer", "bar", "sepultura", "tesseract", "skinny puppy", "yello"
};
for(const std::string& word : get_words_beginning_s(words)) {
std::cout << word << '\n';
}
}
Output:
sepultura
skinny puppy
slayer

I want to remove occurrences of a given letter

I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.
#include <iostream>
#include <string>
using namespace std;
void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
if (text[i] == letter)
{
off++;
}
text[i] = text[i + off];
}
int main() {
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
This should do the job
#include <algorithm>
#include <string>
#include <iostream>
void remove_char(std::string s, char r) {
s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
std::cout << s << std::endl;
}
int main()
{
std::string test = "coffee";
char r = 'f';
remove_char(test, r);
return 0;
}
If u want to do this by hand try this:
std::string removeAllOccurrence(string text, char letter)
{
int off;
int i;
i = off = 0;
string out = "";
for (i = 0; i < text.size(); i++)
{
if (text[i] != letter)
{
out += text[i];
}
}
return out;
}
int main(void)
{
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
system("pause");
return 0;
}
As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too
Kind Regards

How to loop through a string using find() C++

The loop in the program seems to execute at least once, even if there are no occurences of the substring. Why is this?
#include <iostream>
#include <string>
using namespace std;
int countSubstrings(const string& original_string, const string& substr) {
int number_of_ocurrences = 0;
int i = 0;
for (i = original_string.find(original_string, 0); i != string::npos;
i = original_string.find(substr, i)) {
number_of_ocurrences++;
i++;
}
return number_of_ocurrences;
}
int main() {
string input;
while (1) {
cout << "Enter a a line of text: ";
getline(cin, input, '\n');
cout << '\n';
cout << "Number of ocurrences of the word needle: ";
cout << countSubstrings(input, "needle") << '\n';
}
}
Initially when you set i in your for loop you have
original_string.find(original_string, 0)
So you are searching the string for itself which it will find. I believe you meant to have
original_string.find(substr, 0)

How do I replace a string with another string?

I've sat on this problem for quite some time and I can't figure out, what to do.
I am trying to write a programm, that reads a text file, searches and replaces string and saves the file under a new name. Depending on your input with minimum and maximum value as well as inkrement, several files are created.
Everything works except the replacing of a string (function replaceVariable).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <conio.h>
using namespace std;
string replaceVariable(string text1, string oldVariable, long double wert){
cout<< "replace-function open............."<<endl;
size_t foundAt = text1.find(oldVariable); //find position of old variable
cout<<"position old variable: "<<foundAt<<endl;
string newText = to_string(wert); //convert long double 'wert' to string
cout<<"new variable: "<<newText<<endl;
size_t lengthNewText = newText.length(); //find length of new string
string text2= text1.replace(foundAt, lengthNewText, newText); //replace with new string with length 'lengthNewText' starting at position 'foundAt'
return text2;
}
void writeFile ( string text, string filename ){
ofstream myfile;
myfile.open ( filename.c_str() );
myfile << text;
cout<<"file written.............."<<endl;
myfile.close();
}
template <typename T>
std::string to_string(T const& value) {
stringstream sstr;
sstr << value;
return sstr.str();
}
int main(){
ifstream inFile;
inFile.open("C:\\Users\\User\\Desktop\\Test\\testing.txt");//open the input file
if (inFile.is_open()){
cout<< "file open"<<endl<<endl;
stringstream strStream;
strStream << inFile.rdbuf();
string str = strStream.str();
cout << "---------------------------------------------------------------"<<endl;
cout<< str << endl;
cout << "---------------------------------------------------------------"<<endl<<endl;
string line;
string name;
long double minWert = 0;
long double maxWert = 0;
long double inkWert = 0;
cout << "Enter minimum value:" << endl;
cin >> minWert;
cout << "Enter maximum value:" << endl;
cin >> maxWert;
cout << "Enter inkrement:" << endl;
cin >> inkWert;
int numFiles = (maxWert-minWert)/inkWert + 1; //calculation number of files needed
cout << "minimum value: " << minWert << endl;
cout << "maximum value: " << maxWert << endl;
cout << "inkrement: " << inkWert << endl;
cout << "number of files: " << numFiles << endl<<endl<<endl;
string oldVariable = "xyz "; //string to be replaced, xyz followed by 5 spaces
for( int fileNum = 1; fileNum <= numFiles; ++fileNum ) {
cout<< "loop number: "<< fileNum<<endl;
string output = str;
replaceVariable(output, oldVariable, minWert);
cout << "---------------------------------------------------------------"<<endl;
cout << output << endl;
cout << "---------------------------------------------------------------"<<endl<<endl;
string text = output;
name = "C:\\Users\\User\\Desktop\\Test\\comp";
name += to_string( fileNum );
name += ".bdf";
writeFile( text, name );
cout<<minWert<<endl;
minWert = minWert+inkWert;
cout <<"new Minimalwert: "<< minWert<<endl<<endl;
}
inFile.close();
} else{cout << "Unable to open file";}
getch();
return 0;
}
I've already searched numerous sites and googled every thinkable combination.
Do you have any ideas what might help?
If your functionality of the function 'replaceVariable' is right then this might be the issue,
string output = str;
/*function replaceVariable is returning replaced string but you didn't receive
at the calling place and assign back to output(which you are writing in output file)*/
replaceVariable(output, oldVariable, minWert);
So replace like,
string output = replaceVariable(str, oldVariable, minWert);
Several points to be noted in your code.
First, string::find may return npos if the pattern string is not found, you should check that.
Second, string::replace does an inplace replacement on the original string, for better performance you could pass the text1 argument by reference.
Third, replaceVariable only replaces the first occurrence of the variable, is that really what you want?
Here is my version of replacing patterns in a string:
// replaces at most `limit` occurrences of pattern `p` in text `s` with string `repl`.
// if `limit` <= 0, replace all occurrences.
// returns number of replacement that actually took place.
int replace(std::string &s, const std::string &p, const std::string &repl, int limit=0) {
int nrepl = 0;
size_t pos = 0,
plen = p.length(),
rlen = repl.length(),
npos = std::string::npos;
while ((pos = s.find(p, pos)) != npos) {
s.replace(pos, plen, repl);
pos += rlen;
++nrepl;
if (limit > 0 && nrepl >= limit) break;
}
return nrepl;
}
Hope that helps.