Below is a simple code to find 2401 in the string. I do not know what that the number is 2401, it can be any number from 0-9. To find the 4 digit number i want to use "DDDD". The letter D will find a number between 0->9. How do i make it so the compiler realizes that a letter D is a a code to find a 1 digit number.
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::string pattern ;
std::getline(std::cin, pattern);
std::string sentence = "where 2401 is";
//std::getline(std::cin, sentence);
int a = sentence.find(pattern,0);
int b = pattern.length();
cout << sentence.substr(a,b) << endl;
//std::cout << sentence << "\n";
}
try using regular expressions. They can be kind of a pain in the ass, but pretty powerful once mastered. In your case i would recommend using regex_search(), like here:
#include <string>
#include <iostream>
#include <vector>
#include <regex>
using namespace std;
int main()
{
std::smatch m;
std::regex e ("[0-9]{4}"); // matches numbers
std::string sentence = "where 2401 is";
//int a = sentence.find(pattern,0);
//int b = pattern.length();
if (std::regex_search (sentence, m, e))
cout << m.str() << endl;
//cout << sentence.substr(a,b) << endl;
//std::cout << sentence << "\n";
}
If you want to make the exact matching user-specific you can also just ask for the number of digits in the number or the complete regular expression, etc.
Also noted:
[0-9]{4}
means: "any character between 0 and 9 excactly 4 times in a sequence". Have a look here for more informationusing namespace std;
makes the prefix std::
unnecessary for those variable declarationsstd::getline(std::cin, pattern);
could be replaced by cin >> pattern;