替换字符串中的一个字符而不更改字符串大小(C ++)

时间:2015-03-19 22:02:05

标签: c++ string

我遇到问题,因为当string.replace()与char一起使用时,它会改变我的字符串长度。 这是我的代码:

vector<string>::iterator it = matrica.begin();
it = it + i;
it->replace(j,j,1,' ');

2 个答案:

答案 0 :(得分:4)

首先,您需要了解自己在做什么。查看string::replace documentation我们可以看到您正在调用以下重载:

replace(size_t pos, size_t len, size_t n, char c)

,其中

  • pos是要替换的第一个字符的位置,
  • len是要替换的字符数,
  • n是要复制的字符数,
  • c是要复制的角色。

因此,您要从索引j开始用' '替换j个字符。这确实会改变规模。

如果您要做的只是将一个字符替换为另一个字符,则可以执行以下操作之一:

it->at(j) = ' '; // with bounds-checking, safer
(*it)[j] = ' ';  // without bounds-checking, faster

答案 1 :(得分:0)

// replacing in a string
#include <iostream>
#include <string>

int main ()
{
    std::string base="this is a test string.";
    std::string str2="n example";
    std::string str3="sample phrase";
    std::string str4="useful.";

    // replace signatures used in the same order as described above:

    // Using positions:                 0123456789*123456789*12345
    std::string str=base;           // "this is a test string."
    str.replace(9,5,str2);          // "this is an example string." (1)
    str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
    str.replace(8,10,"just a");     // "this is just a phrase."     (3)
    str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
    str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

    // Using iterators:                                               0123456789*123456789*
    str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
    str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
    str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
    str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
    str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
    std::cout << str << '\n';
    return 0;
}

string::replace