2012-03-19 120 views
-1

我知道我已經在不遠的過去問了一個類似於這個問題,我很抱歉要求類似的問題,但我可以解決這個問題,我的代碼如何做到這一點。我想將字符串中的第一個和最後一個字符保持原樣,並替換中間的所有字符。替換字符串中的所有中間字符C++

// finds all banned words 
size_t pos = textWords[i].find(bannedWords[j]); 

// checks through the vector to find all words in the banned list 
if (string::npos != pos) 
{ 
    // replaces the middle character with a * 
    textWords[i].replace(pos + 1 , 1 , 1 , '*'); 
} 

這是我使用它工作的代碼,但它只有三個字母詞的作品,我想它與字的任何長度工作。

再次,我很抱歉,我問過一個類似的問題,但我堅持這一點。

回答

1

如果您在std::string::replace閱讀的文檔,你會看到呼叫您正在使用

textWords[i].replace(pos + 1 , 1 , 1 , '*'); 

意思是「如果你想要改變除了你應該使用的第一個和最後一個字母以外的所有字母,用一個'*'字符替換從位置pos + 1開始的一個字符

textWords[i].replace(pos + 1 , bannedWords[j].size()-2 , bannedWords[j].size()-2 , '*'); 

即,在textWords[i]中爲bannedWords[j].size()-2'*'字符更改bannedWords[j].size()-2字符。

+0

感謝那些完美地工作 – bobthemac 2012-03-19 21:35:27

3

例使用std::string::replace(使用第5次變化的鏈接頁面上):

std::string s = "a-test-string"; 
s.replace(1, s.length() - 2, s.length() -2, '*'); 
1

使用std::string::replace的超載,它接受一個字符並將其複製指定的次數。

#include <string> 
#include <iostream> 

int main() 
{ 
    std::string s("expletive"); 

    s.replace(1, s.size() - 2, s.size() - 2, '*'); 
    std::cout << s << std::endl; 
    return 0; 
} 

輸出:

e*******e