Remove last character from C++ string

2019-03-07 15:51发布

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

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

12条回答
男人必须洒脱
2楼-- · 2019-03-07 16:04
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.

查看更多
冷血范
3楼-- · 2019-03-07 16:07

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
查看更多
Deceive 欺骗
4楼-- · 2019-03-07 16:07

Faced same situation and found such solution:

CString str;
// working with this variable
if (!str.IsEmpty()) // or if(str.GetLength() > 0)
   str.Delete(str.GetLength()-1);

Maybe it will be useful for someone.

查看更多
The star\"
5楼-- · 2019-03-07 16:11

If the length is non zero, you can also

str[str.length() - 1] = '\0';
查看更多
forever°为你锁心
6楼-- · 2019-03-07 16:12

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

st.pop_back();
查看更多
小情绪 Triste *
7楼-- · 2019-03-07 16:13

That's all you need:

#include <string>  //string::pop_back & string::empty

if (!st.empty())
    st.pop_back();
查看更多
登录 后发表回答