如何从字符串中删除字符 [英] How to remove characters from a string
本文介绍了如何从字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有用户输入了电话号码。
For example I have a user input a phone number.
cout << "Enter phone number: ";
INPUT: (555) 555-5555
cin >> phone;
我想从字符串中删除(,)和 - 。我看过字符串删除,查找和替换功能,但我只看到他们操作基于位置。
I want to remove the "(", ")", and "-" characters from the string. I've looked at the string remove, find and replace functions however I only see that they operate based on position.
有一个字符串函数,我可以使用传递一个字符(例如,并删除了字符串中的所有实例)
Is there a string function that I can use to pass a character, "(" for example, and have it remove all instances within a string?
感谢您的时间。
推荐答案
string str("(555) 555-5555");
char chars[] = "()-";
for (unsigned int i = 0; i < strlen(chars); ++i)
{
// you need include <algorithm> to use general algorithms like std::remove()
str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
}
// output: 555 5555555
cout << str << endl;
要用作函数:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
//example of usage:
removeCharsFromString( str, "()-" );
这篇关于如何从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文