如何从c++字符串中删除最后一个字符?
我尝试了st = substr(st.length()-1);但这并没有起作用。
如何从c++字符串中删除最后一个字符?
我尝试了st = substr(st.length()-1);但这并没有起作用。
当前回答
buf.erase(buf.size() - 1);
这假设您知道字符串不是空的。如果是这样,您将得到一个out_of_range异常。
其他回答
不用担心边界检查或使用三元操作符的空字符串:
str.erase(str.end() - (str.length() > 0) ? 1 : 0), str.end());
对于非突变版本:
st = myString.substr(0, myString.size()-1);
buf.erase(buf.size() - 1);
这假设您知道字符串不是空的。如果是这样,您将得到一个out_of_range异常。
如果长度非零,也可以
str[str.length() - 1] = '\0';
在c++ 11中,你甚至不需要长度/大小。只要字符串不为空,就可以执行以下操作:
if (!st.empty())
st.erase(std::prev(st.end())); // Erase element referred to by iterator one
// before the end