How to trim off white space and string except string which is expected??
str ="This is an example sentence."
str1 ="an".
I just want to print "an" in given string . Given string may change everytime just i want to match it with expected string . Below is my code which is giving output but i know its not right way. Guidence would be helpful to optimize my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
int main () {
std::string str= "This is an example sentence.";
std::string str1="an";
std::size_t found = str.find(str1);
cout<<found<<'\n';
int j=found-6;
string str2 = str.substr (found,(j));
cout<<str2<<'\n'; // output: 12
return 0;
}
std::string str= "This is an example sentence.";
std::string str1="an";
Comparing these two string , if str1 content i.e "an" present in str, then only print "an" from str earase ramaining string and whitespace from str. This what i intend to do in my code. Am i doing it in right way???
#include <iostream>
#include <regex>
#include <string>
std::string replace_word( std::string str, std::string word, std::string replacement = " " )
{
// zero or more white space, word boundary, word, word boundary, zero or more white space
std::regex word_re( "\\s*\\b" + word + "\\b\\s*" ) ;
return std::regex_replace( str, word_re, replacement ) ;
}
int main()
{
std::string str = "I know. You know I know. I know you know I know. ""We know Henry knows, and Henry knows we know. ""We're a knowledgeable family." ;
std::cout << str << '\n'
<< replace_word( str, "know" ) << '\n'
<< replace_word( str, "know(s?)" ) << '\n' // know or knows
<< replace_word( str, "know(\\w*)" ) << '\n' ; // know followed by zero or more alphanumeric characters
}
I know. You know I know. I know you know I know. We know Henry knows, and Henry knows we know. We're a knowledgeable family.
I . You I . I you I . We Henry knows, and Henry knows we . We're a knowledgeable family.
I . You I . I you I . We Henry , and Henry we . We're a knowledgeable family.
I . You I . I you I . We Henry , and Henry we . We're a family.