2013-10-23 34 views
1

我是編程的初學者,因此如果我以錯誤的方式處理問題,請儘量簡單。我正在做這個任務。我的目的是從用戶處取出一個字符串,並用另一個符號替換所有的字符。下面的代碼應該可以找到所有的As,然後用* s代替。我的代碼顯示完全意外的結果。還有_deciphered.length()的目的是什麼。如何使用特定符號查找並替換字符串中的所有字符C++

例如: 「我是一個壞男孩」應該變成「我* M * B * d男孩」

那麼我應該實現它所有的大寫和小寫字母和數字,並與更換不同的符號,反之亦然,使一個小編碼 - 解碼方案

#include <iostream> 
#include <string> 
using namespace std; 
string cipher (string); 
void main() 
{ 

    string ciphered, deciphered; 
    ciphered="String Empty"; 
    deciphered="String Empty"; 
    cout<<"Enter a string to \"Encode\" it : "; 
    cin>>deciphered; 
    ciphered=cipher (deciphered); 
    cout<<endl<<endl; 
    cout<<deciphered; 
} 
string cipher (string _deciphered) 
{ 
    string _ciphered=(_deciphered.replace(_deciphered.find("A"), _deciphered.length(), "*")); 
    return _ciphered; 
} 

回答

4

既然你似乎可以用標準庫已經,

#include <algorithm> // for std::replace 

std::replace(_deciphered.begin(), _deciphered.end(), 'A', '*'); 

如果您需要手動完成此操作,然後記住std::string看起來像一個容器char,因此您可以遍歷其內容,檢查每個元素是否爲'A',如果是,則將其設置爲'*'

工作例如:

#include <iostream> 
#include <string> 
#include <algorithm> 

int main() 
{ 
    std::string s = "FooBarro"; 
    std::cout << s << std::endl; 
    std::replace(s.begin(), s.end(), 'o', '*'); 
    std::cout << s << std::endl; 
} 

輸出:

FooBarro

f ** *巴爾

+0

這僅適用直到它找到第一個也是唯一一個返回字。例如,如果我輸入「bad bay」,它會返回「b * d」。我如何得到它返回完整的字符串「b * d b * y」? –

+0

@UsamaKhurshid不,你錯了。它會用'*'替換所有的'A'字符。 – juanchopanza

+0

@UsamaKhurshid我試過了。要麼你正在嘗試其他的東西,或者你的std庫實現被破壞了。 – juanchopanza

1

您可以使用std::replace

std::replace(deciphered.begin(), deciphered.end(), 'A', '*'); 

另外,如果您要替換符合特定條件的多個值,則可以使用std::replace_if

std::replace_if(deciphered.begin(), deciphered.end(), myPredicate, '*'); 

其中myPredicate返回true如果字符的條件匹配被替換。因此,例如,如果您要替換aA,則myPredicate應該返回true,對於aA,並且對於其他字符爲false。

0

我會親自使用正則表達研究取代,以repace「A或」帶*

看一看這個答案有些指針:Conditionally replace regex matches in string

+2

儘管可以使用正則表達式,但std :: replace會簡單得多,而且開銷也小得多。 –

相關問題