[英]Extracting Numbers from Mixed String using stringstream
我正在嘗試使用 stringstream從像 Hello1234 這樣的字符串中提取數字。 我已經編寫了用於在輸入時提取數字的代碼,例如:
你好 1234 世界 9876 你好 1234
給出1234 9876作為輸出,但它不讀取同時具有字符串和數字的混合字符串。 我們如何提取它? - 例如: Hello1234應該給出1234 。
這是我的代碼,直到現在:
cout << "Welcome to the string stream program. " << endl;
string string1;
cout << "Enter a string with numbers and words: ";
getline(cin, string1);
stringstream ss; //intiazling string stream
ss << string1; //stores the string in stringstream
string temp; //string for reading words
int number; //int for reading integers
while(!ss.eof()) {
ss >> temp;
if (stringstream(temp) >> number) {
cout << "A number found is: " << number << endl;
}
}
如果您不限於使用std::stringstream
的解決方案,我建議您查看正則表達式。 例子:
int main() {
std::string s = "Hello 123 World 456 Hello789";
std::regex regex(R"(\d+)"); // matches a sequence of digits
std::smatch match;
while (std::regex_search(s, match, regex)) {
std::cout << std::stoi(match.str()) << std::endl;
s = match.suffix();
}
}
輸出:
123
456
789
在進行流提取之前,只需將字符串中的任何字母字符替換為空格即可。
std::string str = "Hello 1234 World 9876 Hello1234";
for (char& c : str)
{
if (isalpha(c))
c = ' ';
}
std::stringstream ss(str);
int val;
while (ss >> val)
std::cout << val << "\n";
輸出:
1234
9876
1234
您可以將以下代碼與任何類型的流一起使用 - 包括stringstream
。 它從流讀取到第一個數字。 數字被放回流中,然后像往常一樣讀取數字。 實時代碼。
#include <iostream>
using namespace std;
istream& get_number( istream& is, int& n )
{
while ( is && !isdigit( static_cast<unsigned char>( is.get() ) ) )
;
is.unget();
return is >> n;
}
int main()
{
int n;
while ( get_number( cin, n ) )
cout << n << ' ';
}
筆記
關於regex
- 似乎人們忘記/忽略了基礎知識,並且出於某種原因(c++ 純粹主義?),即使是最基本的問題也更喜歡使用大錘。
關於速度- 如果你從圖片中取出流,你就無法擊敗基本的 c。 下面的代碼比正則表達式解決方案快幾十倍,至少比迄今為止的任何答案快幾倍。
const char* get_number( const char*& s, int& n )
{
// end of string
if ( !*s )
return 0;
// skip to first digit
while ( !isdigit( static_cast<unsigned char>( *s ) ) )
++s;
// convert
char* e;
n = strtol( s, &e, 10 );
return s = e;
}
//...
while ( get_number( s, n ) )
//...
添加我的版本:
#include <iostream>
#include <string>
#include <sstream>
int main(){
std::string s;
std::getline(std::cin, s);
std::stringstream ss;
int number;
for(const char c: s){
if( std::isdigit(static_cast<unsigned char>(c)) ){ //Thanks to Aconcagua
ss << c;
} else if ( ss >> number ) {
std::cout << number << " found\n";
}
ss.clear();
}
if(ss >> number)
{
std::cout << number << " found\n";
}
return 0;
}
問題本身非常瑣碎,作為程序員,我們大多數人每天都在解決此類問題。 我們知道任何給定的問題都有很多解決方案,但作為程序員,我們試圖為任何給定的問題找出最好的解決方案。
當我遇到這個問題時,已經有很多有用且正確的答案,但為了滿足我的好奇心,我嘗試對所有其他解決方案進行基准測試,以找出最佳解決方案。
我在上面找到了最好的一個,並且覺得還有一些改進的空間。
所以我在這里發布我的解決方案和基准代碼。
#include <chrono>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
#define REQUIER_EQUAL(x, y) \
if ((x) != (y)) { \
std::cout << __PRETTY_FUNCTION__ << " failed at :" << __LINE__ \
<< std::endl \
<< "\tx:" << (x) << "\ty:" << (y) << std::endl; \
; \
}
#define RUN_FUNCTION(func, in, out) \
auto start = std::chrono::system_clock::now(); \
func(in, out); \
auto stop = std::chrono::system_clock::now(); \
std::cout << "Time in " << __PRETTY_FUNCTION__ << ":" \
<< std::chrono::duration_cast<std::chrono::microseconds>(stop - \
start) \
.count() \
<< " usec" << std::endl;
//Solution by @Evg
void getNumbers1(std::string input, std::vector<int> &output) {
std::regex regex(R"(\d+)"); // matches a sequence of digits
std::smatch match;
while (std::regex_search(input, match, regex)) {
output.push_back(std::stoi(match.str()));
input = match.suffix();
}
}
//Solution by @n314159
void getNumbers2(std::string input, std::vector<int> &output) {
std::stringstream ss;
int number;
for (const char c : input) {
if (std::isdigit(static_cast<unsigned char>(c))) { // Thanks to Aconcagua
ss << c;
} else if (ss >> number) {
output.push_back(number);
}
}
}
//Solution by @The Failure by Design
void getNumbers3(std::string input, std::vector<int> &output) {
istringstream is{input};
char c;
int n;
while (is.get(c)) {
if (!isdigit(static_cast<unsigned char>(c)))
continue;
is.putback(c);
is >> n;
output.push_back(n);
}
}
//Solution by @acraig5075
void getNumbers4(std::string input, std::vector<int> &output) {
for (char &c : input) {
if (isalpha(c))
c = ' ';
}
std::stringstream ss(input);
int val;
while (ss >> val)
output.push_back(val);
}
//Solution by me
void getNumbers5(std::string input, std::vector<int> &output) {
std::size_t start = std::string::npos, stop = std::string::npos;
for (auto i = 0; i < input.size(); ++i) {
if (isdigit(input.at(i))) {
if (start == std::string::npos) {
start = i;
}
} else {
if (start != std::string::npos) {
output.push_back(std::stoi(input.substr(start, i - start)));
start = std::string::npos;
}
}
}
if (start != std::string::npos)
output.push_back(std::stoi(input.substr(start, input.size() - start)));
}
void test1_getNumbers1() {
std::string input = "Hello 123 World 456 Hello789 ";
std::vector<int> output;
RUN_FUNCTION(getNumbers1, input, output);
REQUIER_EQUAL(output.size(), 3);
REQUIER_EQUAL(output[0], 123);
REQUIER_EQUAL(output[1], 456);
REQUIER_EQUAL(output[2], 789);
}
void test1_getNumbers2() {
std::string input = "Hello 123 World 456 Hello789";
std::vector<int> output;
RUN_FUNCTION(getNumbers2, input, output);
REQUIER_EQUAL(output.size(), 3);
REQUIER_EQUAL(output[0], 123);
REQUIER_EQUAL(output[1], 456);
REQUIER_EQUAL(output[2], 789);
}
void test1_getNumbers3() {
std::string input = "Hello 123 World 456 Hello789";
std::vector<int> output;
RUN_FUNCTION(getNumbers3, input, output);
REQUIER_EQUAL(output.size(), 3);
REQUIER_EQUAL(output[0], 123);
REQUIER_EQUAL(output[1], 456);
REQUIER_EQUAL(output[2], 789);
}
void test1_getNumbers4() {
std::string input = "Hello 123 World 456 Hello789";
std::vector<int> output;
RUN_FUNCTION(getNumbers4, input, output);
REQUIER_EQUAL(output.size(), 3);
REQUIER_EQUAL(output[0], 123);
REQUIER_EQUAL(output[1], 456);
REQUIER_EQUAL(output[2], 789);
}
void test1_getNumbers5() {
std::string input = "Hello 123 World 456 Hello789";
std::vector<int> output;
RUN_FUNCTION(getNumbers5, input, output);
REQUIER_EQUAL(output.size(), 3);
REQUIER_EQUAL(output[0], 123);
REQUIER_EQUAL(output[1], 456);
REQUIER_EQUAL(output[2], 789);
}
int main() {
test1_getNumbers1();
// test1_getNumbers2();
test1_getNumbers3();
test1_getNumbers4();
test1_getNumbers5();
return 0;
}
我的平台上的示例輸出
Time in void test1_getNumbers1():703 usec Time in void test1_getNumbers3():17 usec Time in void test1_getNumbers4():10 usec Time in void test1_getNumbers5():6 usec
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.