如何从c++字符串中删除最后一个字符?

我尝试了st = substr(st.length()-1);但这并没有起作用。


对于非突变版本:

st = myString.substr(0, myString.size()-1);

int main () {

  string str1="123";
  string str2 = str1.substr (0,str1.length()-1);

  cout<<str2; // output: 12

  return 0;
}

buf.erase(buf.size() - 1);

这假设您知道字符串不是空的。如果是这样,您将得到一个out_of_range异常。


if (str.size() > 0)  str.resize(str.size() - 1);

std::erase替代方法很好,但我喜欢- 1(无论是基于大小还是结束迭代器)-对我来说,它有助于表达意图。

BTW -真的没有std::string::pop_back吗?-看起来很奇怪。


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

Str.erase (str.rbegin())不能编译,因为reverse_iterator不能转换为normal_iterator。

在这种情况下,c++ 11是你的朋友。


在c++ 11中,你甚至不需要长度/大小。只要字符串不为空,就可以执行以下操作:

if (!st.empty())
  st.erase(std::prev(st.end())); // Erase element referred to by iterator one
                                 // before the end

简单的解决方案,如果你使用c++ 11。也可能是O(1)次:

st.pop_back();

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

参考:std::string::erase(

不需要c++11或c++0x。


这就是你所需要的:

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

if (!st.empty())
    st.pop_back();

如果长度非零,也可以

str[str.length() - 1] = '\0';

#include<iostream>
using namespace std;
int main(){
  string s = "Hello";// Here string length is 5 initially
  s[s.length()-1] = '\0'; //  marking the last char to be null character
  s = &s[0]; // using ampersand infront of the string with index will render a string from the index until null character discovered
  cout<<"the new length of the string "<<s + " is " <<s.length();
  return 0;
}

不用担心边界检查或使用三元操作符的空字符串:

str.erase(str.end() - (str.length() > 0) ? 1 : 0), str.end());