stl 字符串替换
Prerequisite: C++ std::find_first_of()
先决条件: C ++ std :: find_first_of()
Problem Statement:
问题陈述:
Replace all the vowels by '*' using C++ STL function.
使用C ++ STL函数将所有元音替换为“ *”。
Example:
例:
Input:
"includehelp"
Output:
"*ncl*d*h*lp"
Solution:
解:
Of course, we can do it simply by checking each character of the input string. But to elaborate the usage of find_first_of() function.
当然,我们可以简单地通过检查输入字符串的每个字符来做到这一点。 但要详细说明find_first_of()函数的用法。
So the algorithm is our collection of characters would be the vowels.
所以算法是我们的字符集合就是元音。
Let's say that vowels="aeiou" out of which we need to search. So each time we find any character out of those vowels we mark that as '*'. When we will not find any more we will be done.
假设我们需要搜索其中的vowels =“ aeiou” 。 因此,每次我们从这些元音中发现任何字符时,都会将其标记为'*' 。 当我们找不到更多的东西时,我们就会完成。
Just for the example,
仅作为示例,
Input = "includehelp"
So firstly it finds 'i' and replaces with '*'
So input is now "*ncludehelp"
In next iteration it finds u and marks it with '*'
So input is now "*ncl*dehelp"
So on lastly we get
"*ncl*d*h*lp" and processing this step
it returns std::npos and thus it stops.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
cout << "Input the string\n";
cin >> str;
cout << "After replacing all the vowels from the input string\n";
string vowels = "aeiou";
//while there is vowel in the string
while (str.find_first_of(vowels) != string::npos) {
//replaced the vowel with '*'
str[str.find_first_of(vowels)] = '*';
}
cout << "The updated string is: " << str << endl;
return 0;
}
Output:
输出:
Input the string
includehelp
After replacing all the vowels from the input string
The updated string is: *ncl*d*h*lp
The above procedure is computationally expensive that the naïve process where we can run a loop and replace vowels. But the purpose of the program is to show how we can use function find_first_of() efficiently to solve string searching problems.
上面的过程在计算过程上比在幼稚的过程中要昂贵,因为我们可以运行一个循环并替换元音。 但是该程序的目的是说明如何有效使用find_first_of()函数来解决字符串搜索问题。
Also if instead of vowels, we had to search for a long collection of characters it helps.
同样,如果不是元音,我们必须搜索一长串有助于它的字符。
翻译自: https://www.includehelp.com/stl/replace-all-vowels-in-a-string-using-cpp-stl-function.aspx
stl 字符串替换