[英]How to extract numeric fields from a string?
The problem I face is the follows:我面临的问题如下:
I have a string which contains information which is in the following fixed information.我有一个字符串,其中包含以下固定信息中的信息。
club {
level: 210
league: 128
staff: 1451
salary: 3452600
}
club {
level: 211
league: 121
staff: 1451
salary: 3452600
}
... and many more club {...}
I have many entries of club
.我有很多
club
条目。 I want to be able to just extract all the numbers from ALL of the club
in a string in the following format.我希望能够从以下格式的字符串中提取所有
club
所有数字。
Desired Output:期望输出:
2101281451345260021112114513452600
I have the information in the string but I am not able to understand how to efficiently remove the repeating fields from the string such as level:, league:, staff:, club:, salary:, club {}
.我有字符串中的信息,但我无法理解如何有效地从字符串中删除重复字段,例如
level:, league:, staff:, club:, salary:, club {}
。
I would appreciate any help for a simple algorithm which achieves this.对于实现这一目标的简单算法的任何帮助,我将不胜感激。
You don't need to treat your numbers as numbers, treating them as characters is good enough.您不需要将数字视为数字,将它们视为字符就足够了。
To check whether a character is a digit, use isdigit
:要检查字符是否为数字,请使用
isdigit
:
str = ...;
for (char c: str)
if (isdigit(c))
std::cout << c;
You could make use of the erase-remove idiom :您可以使用擦除删除成语:
#include <algorithm>
#include <string>
#include <cctype>
int main()
{
std::string input = "club {"\
"level: 210"\
"league : 128"\
"staff : 1451"\
"salary : 3452600"\
"}";
input.erase(std::remove_if(input.begin(), input.end(), [](char c) { return !std::isdigit(c); }),
input.end());
//string is now "21012814513452600"
return 0;
}
This will remove all non-digits from your string.这将从您的字符串中删除所有非数字。
One idea to extract numbers as numbers: you can replace all unneeded characters by spaces, then get the numbers from the string using stringstream
:将数字提取为数字的一种想法:您可以用空格替换所有不需要的字符,然后使用
stringstream
从字符串中获取数字:
std::string str = ...;
std::string temp = str; // avoid overwriting the original string
for (char& c: temp) // '&' gives you permission to change characters
if (!isdigit(c))
c = ' ';
std::stringstream stream(tmp);
int i;
while (stream >> i)
std::cout << i; // print it or do whatever else
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.