C++从字符串中删除字符
我目前正在尝试在 C++ 中实现从文本字段中删除字符。如果用户按下 Backspace,则执行以下代码。当前没有光标,它应该只删除最后一个字符...
if (mText.length() > 0){
mText.erase( mText.length() - 1, 1);
// mText.resize(mText.length() - 1);
}
第一次工作正常,但如果您再次按退格键,它不会删除任何内容。
我打印了 mText.length() ,它显示长度永远不会改变。我尝试 resize()
字符串,它工作正常,但是当我第一次按 Backspace 时,它会删除 2 个字符。
我希望有人可以解释这种行为并帮助我解决问题。我对内存分配不太了解,所以请耐心等待;)
谢谢
oput
I am currently trying to implement deleting characters from a text field in C++. If the user hits Backspace, the following code is executed. There is currently no cursor, it should just remove the last character...
if (mText.length() > 0){
mText.erase( mText.length() - 1, 1);
// mText.resize(mText.length() - 1);
}
This works fine the first time, but if you hit Backspace again, it does not remove anything.
I printed the mText.length()
and it shows that the length never changes. I tried to resize()
the string, it works fine, but the first time I hit Backspace it removes 2 characters.
I hope someone can explain this behaviour and help me solving the problem. I dont know much about memory allocation, so please be patient with me ;)
Thanks
opatut
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据 this,带有单个 size_t 参数的 string.erase 将删除所有从指定位置到字符串末尾的字符。可以为要删除的字符的数量提供第二size_t参数。
我使用 http://www.ideone.com (查看 此处)并检查 string::length() 是否按预期工作。
我认为问题出在其他地方..
According to this, string.erase with a single size_t parameter will remove all characters from the specified position to the end of the string. A second size_t parameter may be provided for the number of characters to be deleted.
I checked this works as expected using http://www.ideone.com (look here) and also checked that string::length() works as expected.
I think the problem is elsewhere..
为什么不尝试 if(!mText.empty())mText = mText.substr(0, mText.length()-1);?
Why not try
if(!mText.empty())mText = mText.substr(0, mText.length()-1);
?我使用 gdb 发现了我的问题。我发现隐藏的
\b
转义序列在删除最后一个字符后被添加到我的字符串中。它实际上代表退格键,但没有被解释。感谢您的帮助!I found my problem using gdb. I found the hidden
\b
escape sequence which was added to my string after I removed the last character. It actually stands for the backspace, but it was not interpreted. Thank you for your help!