我需要將以下字串拆分為相應的字母和數字
CH1000003
ABC000123
WXYZ10001
我想要的結果是
st1: CH
st2: 1000003
st1: ABC
st2: 000123
st1: WXYZ
st2: 10001
現在我確實有一個作業代碼,但我撰寫的代碼量似乎有點太多了。必須有一個簡單的方法。也許以某種方式在 C 中使用正則運算式?建議?
我的代碼:
std::string idToCheckStr="CH1000003";
//find length of string
int strLength = idToCheckStr.length();
cout << "idToCheckStr: " << idToCheckStr <<endl;
cout << "strLength : " << strLength <<endl;
string::iterator it;
int index = 0;
for ( it = idToCheckStr.begin() ; it < idToCheckStr.end(); it ,index )
{
//check where the numbers start in the string
if (std::isdigit(*it) != 0)
{
cout<< "FOUND NUMBER!" <<endl;
cout<< index << ": " << *it <<endl;
break;
}
cout<< index << ": " << *it <<endl;
}
std::string firstPartStr = idToCheckStr.substr (0,index);
cout << "firstPartStr: " << firstPartStr <<endl;
std::string secondPartStr = idToCheckStr.substr (index,strLength);
cout << "secondPartStr: " << secondPartStr <<endl;
OUTPUT:
idToCheckStr: CH1000003
strLength : 9
0: C
1: H
FOUND NUMBER!
2: 1
firstPartStr: CH
secondPartStr: 1000003
uj5u.com熱心網友回復:
感謝伊戈爾。
size_t first_digit = idToCheckStr.find_first_of("0123456789");
cout << "first_digit: " << first_digit <<endl;
std::string str1 = idToCheckStr.substr (0,first_digit);
cout << "str1: " << str1 <<endl;
std::string str2 = idToCheckStr.substr (first_digit,idToCheckStr.length());
cout << "str2: " << str2 <<endl;
OUTPUT:
first_digit: 2
str1: CH
str2: 1000003
uj5u.com熱心網友回復:
這是處理您的問題的簡單方法之一。我覺得這對你來說更容易理解。
string s = "CH1000003";
// cin >> s; if you waant to read the input
string st1 = "", st2 = "";
for(auto ch : s) {
if(isdigit(ch)) st2 = ch;
else if(isalpha(ch)) st1 = ch;
else {} // if you want something else
}
cout << "st1: " << st1 << endl;
cout << "st2: " << st2 << endl;
uj5u.com熱心網友回復:
您確實可以為此使用正則運算式:
- 模式將是
([A-Z] )([0-9] ),即 1 個或多個大寫字母的任意組合后跟 1 個或多個數字的任意組合。括號允許您捕獲這兩個組,以便以后能夠訪問它們。 std::regex_match(line, matches, pattern)接受輸入line,并嘗試將其與pattern. 如果可以,將匹配項存盤在std::smatch陣列中;其中第一個條目始終是整個匹配項,而連續的條目是針對每個捕獲組的。如果它不能,它只是回傳false。- 如果您需要放松正則運算式,例如在輸入字串之前、之后或中間允許空格,您只需更改模式即可輕松完成:
\s*([A-Z] )\s*([0-9] )\s*.
[演示]
#include <fmt/core.h>
#include <iostream> // cout
#include <regex> // regex_match, smatch
#include <string>
int main() {
std::string line{};
std::regex pattern{R"(([A-Z] )([0-9] ))"};
while (std::getline(std::cin, line)) {
std::smatch matches{};
if (std::regex_match(line, matches, pattern)) {
std::cout << fmt::format("line = '{}', alphabets = '{}', numbers = '{}'\n",
matches[0].str(), matches[1].str(), matches[2].str());
}
}
}
// Outputs:
//
// line = 'CH1000003', alphabets = 'CH', numbers = '1000003'
// line = 'ABC000123', alphabets = 'ABC', numbers = '000123'
// line = 'WXYZ10001', alphabets = 'WXYZ', numbers = '10001'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429312.html
下一篇:如何在if陳述句中使用概念
