如何正确替换字符串中的字符
How to correctly replace a character in a string c++?
#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),否则
但是,您只检查它是否返回true
或false
。您的编译器应该警告您不匹配,因为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)
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数