Hello everybody. How to write a code? | Sololearn: Learn to code for FREE!

+1

Hello everybody. How to write a code?

My question: string str("one hundred and six"); I want to check if sting str contains substring "and". If it is true then erase it and use str otherwise use original string str. Shortly I want to get rid of "and" substr if str has it.

c++

10/22/2021 2:46:12 PM

TeaserCode

13 Answers

New Answer

+4

Try this... #include <iostream> #include <string> using namespace std; int main() { string str = "Two thousand four hundred and twenty"; size_t found = str.find(" and "); if(found != string::npos) { str.erase(found, 4); } cout << str; return 0; }

+2

Use std::string::find() to locate the substring... http://www.cplusplus.com/reference/string/string/find/ then use std::string::erase() to delete the substring... http://www.cplusplus.com/reference/string/string/erase/ The standard library is there to help you. It contains many useful functions, classes, and algorithm implementations. In order to be productive in C++ it is imperative that you study the standard library. The Sololearn course only covers the basics of the language.

+1

If there is no "and" in the string, you don't change the string – no need for a "else", right?

+1

First of all there is no else required. If the substring isn't found there's nothing to do. Secondly, dont search for "and" as you will end up deleting the end of "thousand". surround the "and" with spaces " and ". Thirdly, there is no need to invoke the function twice, that's inefficient. Call the function once and store the value returned. Use this value for the decision and the erase operation if necessary. There is no need to assign the result of the erase method to anything. It operates on the string invoking. Finally, the value returned by std::string::find() is size_t not boolean. If no match is found it returns std::string::npos.

+1

If you want to remove multiples use a do-while loop... #include <iostream> #include <string> using namespace std; int main() { size_t found; string str = "Two thousand and four hundred and twenty"; do { found = str.find(" and "); if(found != string::npos) { str.erase(found, 4); } }while(found != string::npos); cout << str; return 0; }

0

Do you remove just one substring? what if there are more than one substring "and"?

0

bool found = 0; string a("two hundred and six"); //bool found; int d1 = a.length(); if(found) a = a.erase(a.find("and"), 4); } else{????} Yes, I did this but I don't know what goes into else statement

0

Yes, you can have "and" or not. If yes then it must be removed, else goes on.

-1

No there is only one.

-1

-1

-1

Just do it 😁😁😁😁

-1