簡體   English   中英

C ++ std :: string :: assign工作異常

[英]C++ std::string::assign works strange

需要經驗豐富的工程師的幫助。 我已經編寫了一個函數,該函數獲取一個字符串並從中獲取一個子字符串。 子字符串以逗號“,”分隔。 我使用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()在“,”之后使用字符?

std::string::assign (您正在使用的重載)獲取一個位置和一個長度。 沒有兩個職位。 zdevices字符串中的位置。 它僅適用於第一個字符串,因為在這種情況下,您的起始位置為0,因此長度和結束位置相同。

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

如果您只是想基於某些分隔符來分割字符串,為什么不使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM