删除第一个和最后一个字符 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23834624/
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
Remove First and Last Character C++
提问by Putra Fajar Hasanuddin
How to remove first and last character from std::string, I am already doing the following code.
如何从 std::string 中删除第一个和最后一个字符,我已经在执行以下代码。
But this code only removes the last character
但是这段代码只删除了最后一个字符
m_VirtualHostName = m_VirtualHostName.erase(m_VirtualHostName.size() - 1)
How to remove the first character also?
如何删除第一个字符?
回答by Cameron
Well, you could erase()
the first character too (note that erase()
modifies the string):
好吧,您也可以erase()
使用第一个字符(注意erase()
修改字符串):
m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);
But in this case, a simpler way is to take a substring:
但在这种情况下,更简单的方法是取一个子字符串:
m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);
Be careful to validate that the string actually has at least two characters in it first...
首先要小心验证字符串实际上至少有两个字符......
回答by Hernán
My BASIC interpreter chops beginning and ending quotes with
我的 BASIC 解释器用
str->pop_back();
str->erase(str->begin());
Of course, I alwaysexpect well-formed BASIC style strings, so I will abort with failed assert
if not:
当然,我总是期望格式良好的 BASIC 样式字符串,所以assert
如果不是,我将中止失败:
assert(str->front() == '"' && str->back() == '"');
assert(str->front() == '"' && str->back() == '"');
Just my two cents.
只有我的两分钱。
回答by Issam mhedhebi
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}