Search code examples
c++stringsearchediting

Code word search function c++


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";
 }

Solution

  • 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:

    • the simple regular expression provided [0-9]{4} means: "any character between 0 and 9 excactly 4 times in a sequence". Have a look here for more information
    • in your question you mentioned, you wanted the compiler to do the matching. Regular expressions are not matched by the compiler, but at runtime. In that case you could also variable the input string and the regular expression.
    • using namespace std; makes the prefix std:: unnecessary for those variable declarations
    • std::getline(std::cin, pattern); could be replaced by cin >> pattern;