Remove last character from C++ string

后端 未结 10 1256
慢半拍i
慢半拍i 2021-01-29 19:50

How can I remove last character from a C++ string?

I tried st = substr(st.length()-1); But it didn\'t work.

相关标签:
10条回答
  • 2021-01-29 20:18
    if (str.size () > 0)  str.resize (str.size () - 1);
    

    An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.

    BTW - Is there really no std::string::pop_back ? - seems strange.

    0 讨论(0)
  • 2021-01-29 20:22

    str.erase(str.begin() + str.size() - 1)

    str.erase(str.rbegin()) does not compile unfortunately, since reverse_iterator cannot be converted to a normal_iterator.

    C++11 is your friend in this case.

    0 讨论(0)
  • 2021-01-29 20:25

    str.erase( str.end()-1 )

    Reference: std::string::erase() prototype 2

    no c++11 or c++0x needed.

    0 讨论(0)
  • 2021-01-29 20:29

    For a non-mutating version:

    st = myString.substr(0, myString.size()-1);
    
    0 讨论(0)
提交回复
热议问题