如何从C ++中的字符串中删除某些字符? [英] How to remove certain characters from a string in C++?

查看:964
本文介绍了如何从C ++中的字符串中删除某些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个用户输入电话号码。

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, "()-" );

这篇关于如何从C ++中的字符串中删除某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆