0

I am trying to replace a substring of length 1 with a char - but obviously I cannot just stick a char in there. Can I do this on the fly? As in:

for (int j=0; j <= startword.size(); j++) { 
    for (char i='a'; i < 'z'; i++) {
        choices.add(startword.replace(j, 1, string(i));

(but obviously not like that!)

Thanks for your help, this answer is not yet explicit on stackoverflow for c++ (I think only for java). Please excuse some n00bishness here, I am really giving it everything I promise.

Tyler

4

1 回答 1

0

好吧,在 C++ 中,字符串是可变的,您可以使用数组运算符:

for (int j=0; j < startword.size(); j++) 
{ 
    for (char i='a'; i < 'z'; i++) 
    {
        string newChoice = startword;
        newChoice[j] = i;
        choices.add(newChoice);
    }
}

编辑:无法索引newChoice[startWord.size()];更改了 for 循环条件。

你也可以这样做(如果startword很长可能有用):

for (unsigned j=0; j < startword.size(); j++) 
{ 
    char saveChar = startword[j];
    for (char i='a'; i <= 'z'; i++) 
    {
        startword[j] = i;
        choices.add(startword);
    }
    startword[j] = saveChar;
}
于 2013-03-08T05:00:35.390 回答