Change string by index

前端 未结 3 1543
借酒劲吻你
借酒劲吻你 2021-01-13 04:38

I am a beginner in C++ and I am currently working with strings.

My question is why when compiling the code I\'m providing below, I can get the string\'s characters w

3条回答
  •  梦谈多话
    2021-01-13 05:32

    You have not resized your altered string to fit the length of the original string before the loop, thus your code exhibits undefined behavior:

    altered[i] = original[i] + 5; // UB -  altered is empty
    

    To fix this, resize altered before the loop:

    altered.resize(original.size());
    

    Or use std::string::operator+= or similar to append to altered:

    altered += original[i] + 5;
    

    This way, it can be empty before the loop, it will automatically resize itself to contain appended characters.


    Explanation

    The way UB is happening here, is that you're succeeding in writing the data in the static array, which std::string uses for short string optimization (std::string::operator[] does no checks if you're accessing this array past the std::string::size()), but std::string::size() remains 0, as well as std::string::begin() == std::string::end().

    That's why you can access the data individually (again, with UB):

    cout << altered[0] << " " << altered[1] << " " << altered[2] << endl;
    

    but cout << aligned does not print anything, considering simplified operator<< definition for std::string looks functionally like this:

    std::ostream &operator<<(std::ostream &os, std::string const& str)
    {
        for(auto it = str.begin(); it != str.end(); ++it) // this loop does not run
            os << *it;
    
        return os;
    }
    

    In one sentence, std::string is not aware of what you did to its underlying array and that you meant the string to grow in length.


    To conclude, way of doing this transformation:

    std::transform(original.begin(), original.end(),
        std::back_inserter(altered), // or altered.begin() if altered was resized to original's length
        [](char c)
        {
            return c + 5;
        }
    

    (required headers: , )

提交回复
热议问题