当尝试用星号替换数组中的字符串时,为什么会出现错误?

Why is error occurs when trying to replace strings in an array with stars?

本文关键字:为什么 错误 字符串 数组 替换      更新时间:2023-10-16

它不让我替换数组中的字符串,我不知道为什么。

if (t1Array[n] == banArray[o])
{
   //t1Array[n] = "***";
   t1Array[n].replace(1, 2, 3, "***");
   banArrayCount[o] ++;
   t1filterfile << t1Array[n];
}

您似乎想用3个星号替换字符串t1Array[n]的位置1开始的2个字符。

如果是,那么调用将看起来像

t1Array[n].replace( 1, 2, 3, '*' );

这个调用对应于下面的成员函数声明

basic_string& replace(size_type pos, size_type n1, size_type n2, charT c);

或者可以使用以下成员函数

basic_string& replace(size_type pos, size_type n1, const charT* s);

在这种情况下,调用将看起来像

t1Array[n].replace( 1, 2, "***" );

考虑位置从0开始

我想你误解了std::string::replace的工作方式:

#include <iostream>
#include <string>
int main() {
    std::string str = "0123456789";
    std::cout << str.replace(2,3,"***");
}

输出01***56789。被替换的字符数量不需要匹配字符串的长度:

std::cout << str.replace(2,5,"*");
01*789

替换函数具有以下原型-

replace(starting location of replacement,number of characters to be replaced,a pointer to the string)
相关文章: