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

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


当前回答

#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;
}

其他回答

对于非突变版本:

st = myString.substr(0, myString.size()-1);
if (str.size() > 0)  str.resize(str.size() - 1);

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

BTW -真的没有std::string::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;
}

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

st.pop_back();