C++ 在C+中拆分没有空格的字符串+;
我有一个由键值对组成的字符串,但没有分隔符:C++ 在C+中拆分没有空格的字符串+;,c++,string,split,key-value,C++,String,Split,Key Value,我有一个由键值对组成的字符串,但没有分隔符: A0X3Y21.0 所有值都可以是浮点数。如何将此字符串拆分为: A = 0, X = 3, Y = 21.0 我当前的方法是使用strof(),它通常可以正常工作,除了一个恼人的情况,即0在X之前,因此上面的字符串被拆分为: A = 0x3, Y = 21.0 对于解析,通常我使用头中定义的std::stringstreams。此处使用的示例如下: #include <sstream> #include <string>
A0X3Y21.0
所有值都可以是浮点数。如何将此字符串拆分为:
A = 0, X = 3, Y = 21.0
我当前的方法是使用strof(),它通常可以正常工作,除了一个恼人的情况,即0在X之前,因此上面的字符串被拆分为:
A = 0x3, Y = 21.0
对于解析,通常我使用头
中定义的std::stringstream
s。此处使用的示例如下:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::stringstream parser("A0X3Y21.0");
std::stringstream output;
char letter;
double value;
while (parser>>letter&&parser>>value) {
output << letter;
output << " = ";
output << value;
output << " ";
}
std::cout<<output.str();
}
对于解析,通常我使用头
中定义的std::stringstream
s。此处使用的示例如下:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::stringstream parser("A0X3Y21.0");
std::stringstream output;
char letter;
double value;
while (parser>>letter&&parser>>value) {
output << letter;
output << " = ";
output << value;
output << " ";
}
std::cout<<output.str();
}
假设只需打印这些,甚至不必使用strof,只需找到浮点字符串的开头和结尾。这里有一个函数演示了这一点(该函数假设字符串中变量名的长度仅为一个字符,因为从您的示例中可以看出,但如果需要,则不难修复):
要使其基本前提适应您需要做的任何事情应该不会太难。假设您只需要打印这些,您甚至不必使用strof,您只需找到浮点字符串的开头和结尾。这里有一个函数演示了这一点(该函数假设字符串中变量名的长度仅为一个字符,因为从您的示例中可以看出,但如果需要,则不难修复):
要使这一基本前提适应您需要做的任何事情应该不会太难。非常有效,谢谢!我试过了,但它只是显示了整个字符串?有什么区别?while(流){string chunk;stream>>chunk;cout Ahhh我明白了,stringstream使用变量类型来确定如何标记字符串,这非常聪明!@MaxPeglar Willis很高兴你找到了它!优雅的代码…+10非常好用!谢谢!我试过了,但它只显示了整个字符串?有什么区别吗?虽然(stream){string chunk;stream>>chunk;cout Ahhh我理解,stringstream使用变量类型来确定如何标记字符串,这非常聪明!@MaxPeglar Willis很高兴你找到了它!优雅的代码…+10
#include <iostream>
#include <string>
#include <string_view>
void foo(const std::string_view str)
{
for (size_t i = 0; i < str.size(); ++i)
{
std::cout << str[i] << " = ";
size_t float_end_pos = str.find_first_not_of("1234567890.", i + 1) - 1;
std::string_view float_str = str.substr(i + 1, float_end_pos - i);
std::cout << float_str << '\n';
i = float_end_pos;
}
}
int main()
{
foo("A0X3Y21.0");
}
A = 0
X = 3
Y = 21.0