用C ++中的大写字符替换整个字符串

时间:2015-02-03 18:07:55

标签: c++ string replace

我正在寻求帮助来替换整个字符串中的字符。我正在寻找用大写X替换字符串中的所有字符。我尝试实现for循环的范围,但是当我遇到错误时,它似乎不受Microsoft Visual C ++ 2010的支持。所以我决定使用标准的for循环,我也尝试使用替换字符串函数,我假设它将内置在字符串函数库中。但是,我收到了错误。我将不胜感激任何帮助。感谢

#include<iostream>
#include<string>
using namespace std;
int main(){
const char ch = 'X';
char Char1;
string str = {"This is my Book"};

string::size_type n;
for(n = 0; n < str.size(); ++n){ 
    if(str[n] == Char1)
        str[n] = ch;
    cout<< str << endl;

return 0;

}

2 个答案:

答案 0 :(得分:2)

根据我的理解,你想用X替换每个角色。 字符串完全由字符组成,因此您的问题没有多大意义。我假设您的意思是要用X替换所有字母(小写和大写)。

你可以像这样重写你的循环:

for (int n = 0; n < str.size(); ++
    if (((str[n] < 91) && (str[n] > 64)) || ((str[n] < 123) && (str[n] > 96)))
          str[n] = 'X';

与91,64,123和96的比较对应于大写和小写字母的ASCII值的上限和下限。

PS:如果你的意思是别的,请告诉我,我会相应地修改答案。

答案 1 :(得分:2)

一般来说,我收到错误不是很具描述性,而且你的代码是可缩进的。但是,错误在于:

string str = {"This is my Book"};

你可能意味着:

string str {"This is my Book"};

前者创建初始化列表并尝试将其分配给str;后者只是用给定的参数构造一个字符串。

但是,VS 2010不支持初始化列表,因此您需要执行此操作:

string str("This is my Book");

此外,你的for循环中有一个冗余的开括号,它永远不会与结束的那个匹配。

另一个问题:Char1永远不会被初始化,因此它可以保留任何内容。它在目前的背景下似乎毫无用处。

使用STL迭代器也可以更好地完成for循环:

for (string::iterator it = str.begin(); it != str.end(); ++it)
    *it = ch;

您的固定代码:

#include <iostream>
#include <string>

using namespace std;

int main() {
    const char ch = 'X';
    string str("This is my Book");

    for (string::iterator it = str.begin(); it != str.end(); ++it)
        // for each character in str, set it to ch
        *it = ch;
    cout << str << endl;

    return 0;
}

如果您只想替换字母,请执行以下操作:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {
    const char ch = 'X';
    string str("This is my Book");

    for (string::iterator it = str.begin(); it != str.end(); ++it)
        if (isalpha(*it)) // make sure we're replacing a letter
            *it = ch;
    cout << str << endl;

    return 0;
}

但是,由于您只是填写字符串,因此有更好的方法:

#include <iostream>
#include <string>

using namespace std;

int main() {
    const char ch = 'X';
    string str("This is my Book");

    str = string(str.size(), 'X');
    // This is a version of the std::string constructor that takes
    // a number (N) and a character and duplicates the character N
    // times.
    cout << str << endl;

    return 0;
}

或者,更好的是,使用lambdas和for_each:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    const char ch = 'X';
    string str("This is my Book");

    // for_each takes an iterator to the start and end of any STL
    // container. It then calls the given function on each element in 
    // the iterator. This lambda replaces the character with ch.
    for_each(str.begin(), str.end(), [](char& c) { c = ch; });
    cout << str << endl;

    return 0;
}