如何正确替换字符串中的字符

How to correctly replace a character in a string c++?

本文关键字:字符 字符串 何正确 替换      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string passCode;
passCode = "1 ";
int i;
for(i =0; i < passCode.length();i++){
if(isspace(passCode.at(i)) == true){
passCode.replace(i,1,"_");
}
}
cout << passCode << endl;
return 0;
}

上面的代码,我的指示是[用'_'替换2字符字符串passCode中的任何空格' '。如果不存在空格,程序不应该打印任何东西。[/p>

用我的代码当前的方式,它输出"1"。当我用条件检查false而不是true来运行它时,它打印"_"。我不明白为什么要这样做,有人看到我没有看到的问题吗?我不允许使用这个算法。头。我也只允许在main中工作,没有函数或导入的头/类。

对于单个字符,使用std::replace算法可能更容易:

std::replace(passCode.begin(), passCode.end(), ' ', '_');

如果你不能使用算法头,你可以推出你自己的replace函数。它可以通过一个简单的循环来完成:

template<typename Iterator, typename T>
void replace(Iterator begin, Iterator end, const T& old_val, const T& new_val)
{
    for (; begin != end; ++begin)
        if (*begin == old_val) *begin = new_val;
}

用我的代码当前的方式,它输出"1"。当我在条件检查为false而不是true时运行它时,它打印"_"

isspace在传递一个空格时返回一个非零值。这个不一定是1。另一方面,布尔值true通常设置为1。

比较isspace的返回值和true时,如果它们不完全相等会发生什么?具体来说,如果true为1且isspace返回非零值怎么办?

我认为这就是这里正在发生的事情。if条件失败,因为这两个值不同。所以空格不会被'_'代替

你的问题是你使用isspace。如果你阅读isspace的文档,它说:


返回值如果c确实是空白字符,则不等于零的值(即true)。0(即false),否则

但是,您只检查它是否返回truefalse。您的编译器应该警告您不匹配,因为isspace返回int,而您正在检查bool

更改为以下代码应该可以工作:

if(isspace(passCode.at(i)) != 0) {
    passCode.replace(i,1,"_");
}

我的回答是基于更具体地围绕你的问题和你的评论说,你不能使用任何标题除了你所包含的。juanchopanza提供了一个更好的解决方案,您甚至应该尽可能地使用标准库,而不是编写自己的代码。

您也可以使用std::string::find控制while循环并将空格替换为std::string::replace

std::string test = "this is a test string with spaces ";
std::size_t pos = 0;
while ((pos = test.find(' ', pos)) != std::string::npos)
{
    test.replace(pos, 1, "_");
    pos++;
}
std::cout << test;
<<p> 生活例子/kbd>

如上所述,isspace不返回bool值。相反,它返回int,其中非零值表示真,零值表示假。您应该这样写支票:

if (isspace(passCode.at(i)) != 0)