C++ 如何正确替换字符串c++;? #包括 #包括 #包括 使用名称空间std; int main(){ 字符串密码; 密码=“1”; int i; 对于(i=0;i

C++ 如何正确替换字符串c++;? #包括 #包括 #包括 使用名称空间std; int main(){ 字符串密码; 密码=“1”; int i; 对于(i=0;i,c++,string,replace,C++,String,Replace,对于单个字符,使用算法可能更容易: #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){ p

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

#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;
}
如果您不能使用算法标题,您可以推出自己的
replace
函数。可以通过一个简单的循环完成:

std::replace(passCode.begin(), passCode.end(), ' ', '_');
模板
无效替换(迭代器开始、迭代器结束、常量T和旧值、常量T和新值)
{
for(;begin!=end;++begin)
如果(*开始==旧值)*开始=新值;
}
我的代码当前是这样的,它输出“1”。当我在运行它时检查条件是否为false而不是true时,它会打印“\u1”

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

当我们将isspace的返回值与true进行比较时,当它们不完全相等时会发生什么? 具体来说,如果true为1,而isspace只返回一些非零值,该怎么办

我认为这就是这里发生的情况。if条件失败,因为这两个值不同。因此,空格没有被“u”替换。

如上所述,isspace不返回bool。相反,它返回int,其中非零值表示true,零值表示false。您应该这样写检查:

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;
}

你的问题是你对
isspace
的使用。如果你读到它会说:

返回值
如果c确实是一个空白字符,则该值不同于零(即true)。否则为零(即false)

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

更改为以下代码应适用于您:

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

我的回答更具体地基于您的问题和您的评论,您说除了您包含的内容之外,您不能使用任何标题。一个更好的解决方案是,您应该尽可能地使用标准库,而不是编写自己的代码。

您也可以使用和rep控制的while循环来实现这一点用花边系空间

std::string test=“这是一个带空格的测试字符串”;
标准:尺寸\u t位置=0;
while((pos=test.find(“”,pos))!=std::string::npos)
{
测试。更换(位置1,“”);
pos++;
}

std::如果
+
isspace
可能更适合这里,我想
replace\u是否可以。它也用于OP的代码中。@cad说明中说“将任何空格”替换为“\u”,所以使用
isspace
可以做得更多。这不起作用,它说replace不是std::@Flower如果你阅读链接中的文档并包含所需的标题,它会起作用。@Flower请不要浪费人们的时间。如果你有荒谬的限制,应该在你的问题中解释清楚。
std::string
是模板的typedef,因此您已经违反了自己的规则。我明白了,这是如何向我解释的:如果空白是空格(“”)//true是空格('\n')//true是空格('\n')//true是空格('x'))//错,难怪它不起作用。谢谢alot@Flower在C/C++中if/while和其他条件语句如何工作的上下文中,假设非零的值为TRUE,等于零的值为FALSE。请注意,这将不仅仅是“替换任何空格
。。是的,在我的程序中,它的评估结果为正值,感谢您的帮助。
if(isspace(passCode.at(i)) != 0) {
    passCode.replace(i,1,"_");
}
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;