给定一个字符串S和一个字符C ,任务是从给定的字符串删除所有出现的字符C 。
例子:
Input:vS = “GFG IS FUN”, C = ‘F’
Output:GG IS UN
Explanation:
Removing all occurrences of the character ‘F’ modifies S to “GG IS UN”.
Therefore, the required output is GG IS UN
Input: S = “PLEASE REMOVE THE SPACES”, C = ‘ ‘
Output: PLEASEREMOVETHESPACES
Explanation:
Removing all occurrences of the character ‘ ‘ modifies S to “GG IS UN”.
方法:想法是使用C++ STL中的erase()方法和remove()函数。下面是从字符串删除所有出现的字符的语法。
S.erase(remove(S.begin(), S.end(), c), S.end())
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
#include
using namespace std;
// Function to remove all occurences
// of C from the string S
string removeCharacters(string S, char c)
{
S.erase(remove(
S.begin(), S.end(), c),
S.end());
return S;
}
// Driver Code
int main()
{
// Given String
string S = "GFG is Fun";
char C = 'F';
cout << "String Before: " << S << endl;
// Function call
S = removeCharacters(S, C);
cout << "String After: " << S << endl;
return 0;
}
输出:
String Before: GFG is Fun
String After: GG is un
时间复杂度: O(N 2 )
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live