Remove last character from C++ string

后端 未结 10 1255
慢半拍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:06

    Simple solution if you are using C++11. Probably O(1) time as well:

    st.pop_back();
    
    0 讨论(0)
  • 2021-01-29 20:08

    If the length is non zero, you can also

    str[str.length() - 1] = '\0';
    
    0 讨论(0)
  • 2021-01-29 20:12

    With C++11, you don't even need the length/size. As long as the string is not empty, you can do the following:

    if (!st.empty())
      st.erase(std::prev(st.end())); // Erase element referred to by iterator one
                                     // before the end
    
    0 讨论(0)
  • 2021-01-29 20:13
    int main () {
    
      string str1="123";
      string str2 = str1.substr (0,str1.length()-1);
    
      cout<<str2; // output: 12
    
      return 0;
    }
    
    0 讨论(0)
  • 2021-01-29 20:14
    buf.erase(buf.size() - 1);
    

    This assumes you know that the string is not empty. If so, you'll get an out_of_range exception.

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

    That's all you need:

    #include <string>  //string::pop_back & string::empty
    
    if (!st.empty())
        st.pop_back();
    
    0 讨论(0)
提交回复
热议问题