使用分隔符空格解析字符串,但字符串也包含空格
Parse string with delimiter whitespace but having strings include whitespace as well?
我有一个文本文件,其中包含州名及其各自的缩写。它看起来像这样:
Florida FL
Nevada NV
New York NY
因此,州名称和缩写之间的空格数量不同。我想提取名称和缩写,我想使用带有空格的 getline 作为分隔符,但我在"纽约"等名称中的空格有问题。我可以使用什么功能?
您知道缩写始终是两个字符。
因此,您可以阅读整行,并将其从末尾拆分为两个字符(可能使用substr
(。
然后修剪第一个字符串,您有两个漂亮的字符串用于名称和缩写。
系统方法是分析所有可能的输入数据,然后在文本中搜索模式。在您的情况下,我们分析问题并发现
- 在字符串的末尾,我们有一些连续的大写字母
- 在此之前,我们有州名
因此,如果我们搜索状态缩写模式并将其拆分,则状态的全名将可用。但也许有尾随和前导空格。我们将删除它,然后结果就在那里。
对于搜索,我们将使用一个 std::regex
.模式为:1 个或多个大写字母,后跟 0 或多个空格,后跟行尾。其正则表达式为:"([A-Z]+)\s*$"
如果可用,则结果的前缀包含完整的状态名。我们将删除前导空格和尾随空格,仅此而已。
请看:
#include <iostream>
#include <string>
#include <sstream>
#include <regex>
std::istringstream textFile(R"( Florida FL
Nevada NV
New York NY)");
std::regex regexStateAbbreviation("([A-Z]+)\s*$");
int main()
{
// Split of some parts
std::smatch stateAbbreviationMatch{};
std::string line{};
while (std::getline(textFile, line)) {
if (std::regex_search(line, stateAbbreviationMatch, regexStateAbbreviation))
{
// Get the state
std::string state(stateAbbreviationMatch.prefix());
// Remove leading and trailing spaces
state = std::regex_replace(state, std::regex("^ +| +$|( ) +"), "$1");
// Get the state abbreviation
std::string stateabbreviation(stateAbbreviationMatch[0]);
// Print Result
std::cout << stateabbreviation << ' ' << state << 'n';
}
}
return 0;
}
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 移除前面有空格的前2个字符串
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 使用另一个字符串从字符串中删除空格
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- C++ "noskipws"没有按预期工作,如何正确允许字符串中的空格?
- 在 c++ 中逐行阅读字符串,不要以空格停止
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 如何存储包含多个空格的字符串 c++
- 在特定位置为字符串添加空格
- 有没有办法在 c++ 中获取带有空格的完整字符串?
- C++完全复制要字符串的字符列表,而不会忽略多个空格
- Winsock2:当我尝试发送带有空格的字符串时,该函数在遇到空格时似乎停止发送
- 从没有空格的字符串中提取整数
- 用于拆分空格字符串的程序不起作用
- 解析C++中的完整(从头到尾)字符串,包括所有空格
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 如何获取我的区域设置的空格字符串?