如何替换整个字符串中字符的每个匹配项?在 C++ 中
how to replace every match of a charecter in the entire string?? in c++
这是我的代码,当我给出输入时aeiou AEIOU
它只出来xxxxx
我哪里出错了??? 我想替换整个字符串中的每个元音,但我只对第一个单词这样做,我的代码是错误的吗?
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class remove_vowels_class
{
private:
public:
void remove_vowels_accept(string the_string)
{
std::replace(the_string.begin(),the_string.end(),'a','x');
std::replace(the_string.begin(),the_string.end(),'A','x');
std::replace(the_string.begin(),the_string.end(),'e','x');
std::replace(the_string.begin(),the_string.end(),'E','x');
std::replace(the_string.begin(),the_string.end(),'i','x');
std::replace(the_string.begin(),the_string.end(),'I','x');
std::replace(the_string.begin(),the_string.end(),'o','x');
std::replace(the_string.begin(),the_string.end(),'O','x');
std::replace(the_string.begin(),the_string.end(),'u','x');
std::replace(the_string.begin(),the_string.end(),'U','x');
std::replace(the_string.begin(),the_string.end(),'~',' ');
cout<<"the replaced string is :"<<the_string<<endl;
}
};
int main()
{
remove_vowels_class maniobj;
string input_string;
cout<< "Enter a string to replace all vowels:"<<endl;
cin>>input_string;
std::replace(input_string.begin(),input_string.end(),' ','~');
maniobj.remove_vowels_accept(input_string);
cin>>input_string;
将从输入中提取文本,直到它到达空格,因此只有输入的第一个单词会被放入input_string。使用字符串库中的std::getline
获取整行。
使用 std::getline
而不是 cin>>input_string
cin>>input_sting
只会读取输入字符串直到空格。
std::getline( std::cin, input_string);
就像
scanf
一样,cin
忽略空格。看看这个。尝试gets
http://www.cplusplus.com/reference/cstdio/gets/以读取字符串。
编辑:正如@James里德指出的那样,gets
正在从标准中删除。另一个答案提供了另一种选择。不过,我将答案留待将来参考。
你需要使用 std::getline,这是一个更干净/更简单的 c++11 实现。
#include <string>
#include <iostream>
std::string replace_vowels(const std::string & str) {
static const char vowels[] = {'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'};
std::string cp(str);
for(std::size_t i = 0; i < str.length(); ++i) {
auto & ch = str[i];
for(auto & v : vowels) {
if(ch == v) {
cp[i] = 'x';
break;
}
}
}
return std::move(cp);
}
int main() {
std::string input, output;
std::cout << "Enter a string to replace all vowels : ";
std::getline(std::cin, input);
output = replace_vowels(input);
std::cout << "Input : " << input << " / Output : " << output << std::endl;
}
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存