C ++ std :: string :: assign很奇怪

时间:2014-07-29 18:02:46

标签: c++ string

需要经验丰富的工程师提供帮助。我写了一个函数,它获取一个字符串并从中获取一个子字符串。子串用逗号','分隔。我使用assign()函数来复制子字符串。我的代码:

void my_function(string devices)
{
    unsigned int last=0;
    unsigned int address;
    printf("whole string: %s\n",devices.c_str());

    for (unsigned int z=0; z<devices.size();z++)
    {
        if(devices[z]==',')     
        {
            zone_name.assign(devices,last,z);
            printf("device:%s\n",zone_name.c_str());
            address=get_kd_address_by_name(zone_name);
            last=z+1;
            if(address>0)
            {   
                //doing stuff
            }
        }
    }
}

我的问题:只有第一次迭代才有效。 在终端我得到:

whole string: device1,device2,device3,000001029ADA
device:device1
device:device2,device3
device:device3,000001029ADA

为什么assign()接受','?

之后的字符

2 个答案:

答案 0 :(得分:8)

std::string::assign(您正在使用的重载)占据位置和长度。不是两个职位。 zdevices字符串中的一个位置。它仅适用于第一个字符串,因为在这种情况下,您的起始位置为0,因此长度和结束位置是相同的。

unsigned int length = z - last;
zone.assign(devices, last, length);

答案 1 :(得分:1)

如果您只是尝试根据某个分隔符拆分字符串,为什么不使用boost::split

#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>
#include <iostream>

int main(int, char*[])
{
    std::string input("foo,bar,baz");
    std::vector<std::string> output;

    std::cout << "Original: " << input << std::endl;      
    boost::split( output, input, boost::is_any_of(std::string(",")) );
    for( size_t i=0; i<output.size(); ++i )
    {
        std::cout << i << ": " << output[i] << std::endl;
    }

    return 0;
}

打印:

Original: foo,bar,baz
0: foo
1: bar
2: baz