首頁 > 後端開發 > C++ > 主體

使用正規表示式的C++程式列印每個單字的首字母

王林
發布: 2023-08-26 21:33:17
轉載
1122 人瀏覽過

使用正規表示式的C++程式列印每個單字的首字母

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>);
登入後複製
在這個迭代器中,前兩個參數是起始和結束指標的 string object. The third parameter is the given regular expression object which we have 在之前創建。第四個參數是子匹配。當子匹配為0時,它將 傳回那些來自符合的元素(在符合時)的內容,當 submatch is -1, it represents where the matching is not done (reverse of the submatch 0). submatch為-1,表示符合未完成的位置(與submatch 0相反)

演算法

  • 將字串 s 作為輸入
  • define regular expression with '\b[a-zA-Z]'
  • 對s使用表達式進行匹配
  • 定義一個迭代器物件來只讀取匹配項
  • for each item in iterator object, do
    • 顯示項目
  • 結束循環

Example

#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, 
登入後複製

Conclusion

表達式在字串中用於匹配常見模式 表達式庫(正規表示式)在所有高階語言中都可用,包括Java,Python Javascript,Dart和C 。它有許多應用。一個正規表示式, reads the first character of each word has been defined in this article. We need an iterator ,它會逐一讀取每個匹配的字符,以便循環遍歷它們。

以上是使用正規表示式的C++程式列印每個單字的首字母的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!