码字搜索函数c++
Code word search function c++
下面是在字符串中查找 2401 的简单代码。 2401这个数字我不知道是什么,它可以是0-9中的任意数字。要找到我想使用的 4 位数字 "DDDD"。字母 D 将找到 0->9 之间的数字。我该怎么做才能让编译器意识到字母 D 是用于查找 1 位数字的代码。
#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";
}
尝试使用 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(),如下所示:
#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";
}
如果你想精确匹配用户特定的,你也可以只询问数字中的位数或完整的正则表达式等
还注意到:
- 提供的简单正则表达式
[0-9]{4}
表示:"any character between 0 and 9 excactly 4 times in a sequence"。查看here了解更多信息
- 在您提到的问题中,您希望编译器进行匹配。正则表达式不是由编译器匹配的,而是在运行时匹配的。在这种情况下,您还可以改变输入字符串和正则表达式。
using namespace std;
使得前缀 std::
对于那些变量声明来说是不必要的
std::getline(std::cin, pattern);
可以替换为 cin >> pattern;
下面是在字符串中查找 2401 的简单代码。 2401这个数字我不知道是什么,它可以是0-9中的任意数字。要找到我想使用的 4 位数字 "DDDD"。字母 D 将找到 0->9 之间的数字。我该怎么做才能让编译器意识到字母 D 是用于查找 1 位数字的代码。
#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";
}
尝试使用 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(),如下所示:
#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";
}
如果你想精确匹配用户特定的,你也可以只询问数字中的位数或完整的正则表达式等
还注意到:
- 提供的简单正则表达式
[0-9]{4}
表示:"any character between 0 and 9 excactly 4 times in a sequence"。查看here了解更多信息 - 在您提到的问题中,您希望编译器进行匹配。正则表达式不是由编译器匹配的,而是在运行时匹配的。在这种情况下,您还可以改变输入字符串和正则表达式。
using namespace std;
使得前缀std::
对于那些变量声明来说是不必要的std::getline(std::cin, pattern);
可以替换为cin >> pattern;