简体   繁体   English

在 C++ 中拆分没有空格的字符串

[英]Splitting a string with no spaces in C++

I have the a string which consists of key value pairs but no delimiter character:我有一个由键值对组成但没有分隔符的字符串:

A0X3Y21.0

All values may be floats.所有值都可以是浮点数。 How can I split this string up into:如何将此字符串拆分为:

A = 0, X = 3, Y = 21.0

My current method was to use strtof() which works generally except for one annoying case where an 0 is before an X and so the above string is instead split into:我目前的方法是使用 strtof() ,它通常可以工作,除了一个烦人的情况,即 0 在 X 之前,因此上面的字符串被拆分为:

A = 0x3, Y = 21.0

For parsing, normally I use std::stringstream s, defined in the header <sstream> .对于解析,通常我使用在 header <sstream>中定义的std::stringstream An example use here:此处使用示例:

#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();
}

This would output this:这将是 output 这个:

A = 0 X = 3 Y = 21

Assuming you just have to print these, you don't even have to use strtof , you just have to find the beginning and end of the float string.假设你只需要打印这些,你甚至不必使用strtof ,你只需要找到浮点字符串的开头和结尾。 Here's a function that demonstrates this (this function assumes that the length of the variable names in the string are only one character since from your example, but it isn't too hard to fix that if need be):这是一个 function 演示了这一点(这个 function 假设字符串中变量名的长度从您的示例开始只有一个字符,但如果需要,修复它并不难):

#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");
}

Output: Output:

A = 0
X = 3
Y = 21.0

And it shouldn't be too hard to adapt the basic premise of this to whatever you need to do.并且将其基本前提适应您需要做的任何事情都不应该太难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM