A useful tool for string operations is regex. This may be found in virtually all high-level 当前的编程语言,包括C++。正则表达式(Regex)被用作 通用搜索模式。例如,通过构建一个简单的字符串 被称为正则表达式,我们可以使用至少实现密码验证逻辑 一个大写字母,一个小写字母,一个数字,一个特殊字符,并且总长度至少为 8个字符。
In this tutorial, we'll look at how to use C++ to display only the first letters of words included 在指定的字符串内。在这里,我们将看一个使用空格来分隔单词的句子 无论字符是大写还是小写,计算机都会读取 将字符串使用正则表达式分割,并返回每个单词的第一个字符。
To use regular expressions, we need to import the regex library using the ‘regex’ header. To 使用正则表达式,我们需要以下语法 -
regex obj_name( <regular expression> )
After defining regex, we can use them in multiple ways. We will see our intended approach 在下面。现在要从单词中读取第一个字符,正则表达式的语法将会是这样的 下面的内容为:
\b[a-zA-Z]
在这里,‘b’表示单词的开头。[a-zA-Z]表示大写或小写字母 lowercase letters which are in the range of ‘a’ to ‘z’ or ‘A’ to ‘Z’. And only one of them is taken. 现在让我们看一下正在用于读取所有选定匹配项的迭代器对象 -
regex_token_iterator<string::iterator> iterator_name( <begin pointer of string>, <ending pointer of string>, <regular expression>, <submatch>);
#include <iostream> #include <regex> using namespace std; string solve( string s){ string ret = ""; regex e("\b[a-zA-Z]"); regex_token_iterator<string::iterator> i(s.begin(), s.end(), e, 0); regex_token_iterator<string::iterator> end; while (i != end) { ret += (*i++); ret += ", "; } return ret; } int main(){ string s = "A string to read only the first letter of words"; cout << "Given String: " << s << endl; cout << "The first letter of each word: " << solve( s ) << endl; s = "Central Pollution Control Board"; cout << "Given String: " << s << endl; cout << "The first letter of each word: " << solve( s ) << endl; }
Given String: A string to read only the first letter of words The first letter of each word: A, s, t, r, o, t, f, l, o, w, Given String: Central Pollution Control Board The first letter of each word: C, P, C, B,
以上是使用正则表达式的C++程序打印每个单词的首字母的详细内容。更多信息请关注PHP中文网其他相关文章!