从 C++ 字符串中删除最后一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2310939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:58:59  来源:igfitidea点击:

Remove last character from C++ string

c++stringsubstring

提问by skazhy

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

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

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

我试过了,st = substr(st.length()-1);但没有用。

采纳答案by Matthieu M.

For a non-mutating version:

对于非变异版本:

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

回答by mpgaillard

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

如果您使用的是 C++11,那么简单的解决方案。也可能是 O(1) 时间:

st.pop_back();

回答by Steve314

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

An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.

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

BTW - Is there really no std::string::pop_back ? - seems strange.

顺便说一句 - 真的没有 std::string::pop_back 吗?——似乎很奇怪。

回答by RC.

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

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

这假设您知道该字符串不为空。如果是这样,你会得到一个out_of_range例外。

回答by ribamar

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

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

Reference: std::string::erase() prototype 2

参考:std::string::erase() 原型 2

no c++11 or c++0x needed.

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

回答by jcrv

That's all you need:

这就是你所需要的:

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

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

回答by codaddict

int main () {

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

  cout<<str2; // output: 12

  return 0;
}

回答by Zebra

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

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

str.erase(str.rbegin())does not compile unfortunately, since reverse_iteratorcannot be converted to a normal_iterator.

str.erase(str.rbegin())不幸的是无法编译,因为reverse_iterator无法转换为 normal_iterator。

C++11 is your friend in this case.

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

回答by Michael Goldshteyn

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

使用 C++11,您甚至不需要长度/大小。只要字符串不为空,您就可以执行以下操作:

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

回答by Jan Glaser

If the length is non zero, you can also

如果长度不为零,您也可以

str[str.length() - 1] = '##代码##';