stl 字符串替换_使用C ++ STL函数替换字符串中的所有元音

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 字符串替换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值