简体   繁体   中英

how to trim vector char array or string?

I am following this code to trim

    std::string tcp_read(int listen_at_port=8001){

    using namespace std;
    using namespace boost::algorithm;
    std::vector<char> received_data(512); 
    tcp_read(received_data, listen_at_port);
    string str1(received_data.begin(),received_data.end());
    trim_right(str1);
    return str1;
}

I stepped throught the code, my received_data is generally = "add 8002 (here onwards buffer is filled with spaces till the [511th] position)"

now when I did trim_right I expected the str1 size to become 8, but its still 512 when its returning, why?

How do i get actually trim and change the size so that the string just accomodates till the last non space character

As explained in the other answer , your vector is filled with zeros, which are not considered whitespace , so trim_right doesn't strip those from the string. An easy fix to your problem is to not construct the string using the begin and end iterators of the vector, but use the string( char const * ) constructor. This also eliminates the call to boost::trim_right .

std::string tcp_read(int listen_at_port=8001)
{
    using namespace std;

    std::vector<char> received_data(512); 
    tcp_read(received_data, listen_at_port);

    return string( received_data.data() );
    // or return string( &received_data[0] );
}

trim_right only removes all trailing whitespaces. When you declare received_data it is initialized with all zeros. When you read data from the socket the data at the end of the buffer is [most certainly] not composed of spaces.

I suggest that when you call tcp_read() you return the number of bytes that were actually read from the socket and do recieved_data.resize(byte_count); instead of calling trim_right . Also if the data received over the socket can contain zeros you should probably be returning a vector instead of string .

[Kudos to Praetorian for pointing out that it removes all whitespaces ]

That's silly, but in case whitespaces aren't really whitespaces:

string str1(received_data.begin(), 
    find(received_data.begin(), received_data.end(), received_data[511]) );

And if they are:

string str1(received_data.begin(), 
    find( 
        find(received_data.begin(), received_data.end(), ' ') + 1, 
        received_data.end()) );

But that's just some hacks, trim right should work just fine, there's probably something wrong with the received_data.

And yes, trimming the string wouldn't reallocate any memory anyway, so it might be ok to store it as it is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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