2016-11-09 25 views
0

標題說這一切 - 我的字符串將只由空格分隔的數字組成,例如, 1 0 3 0 4 0 7 0.我想要做的是刪除最常出現的字符,然後得到1 3 4 7.總是會有一個重複的數字。我試過,但它不僅能消除重複的,不是字符的實際發生:從字符串中刪除最頻繁的字符 - C++

string newString = "1 0 3 0 4 0 7 0"; 
sort(newString.begin(), newString.end()); 
newString.erase(unique(newString.begin(), newString.end()), newString.end()); 

我也試着遍歷由字符串字符,然後取出一個是大多數發生,但它不't work:

void countCharacters(const char n[], char count[]) 
{ 
int c = 0; 
while (n[c] != '\0') 
    { 
    if (n[c] >= '0' && n[c] <= '9') 
     count[n[c] - '0']++; 
    } 
} 

void myFunction() 
{ 
string newString = "1 0 3 0 4 0 7 0"; 
char count[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; 
const char *charString = newString.c_str(); 
countCharacters(charString, count); 
for (unsigned int z = 0; z < strlen(charString); z++) 
     { 
      if (count[z] > 1) 
       { 
       newString.erase(remove(newString.begin(), newString.end(), count[z]), newString.end()); 
       } 
     } 
} 

任何幫助將不勝感激! :)

回答

0

後聲明的字符串試試這個代碼

void solve() { 
string s = "1 0 3 0 4 0 7 0"; 
    int mx_count = 0, cnt[10] = {0}; 
    char mx_occ = '0'; 
    for(int i = 0; i < int(s.size()); i++) { 
    if('0' <= s[i] && s[i] <= '9') { 
     cnt[s[i] - '0']++; 
     if(cnt[s[i] - '0'] > mx_count) 
     mx_count = cnt[s[i] - '0'], mx_occ = s[i]; 
    } 
    } 
    queue<int> idxs; 
    for(int i = 0; i < int(s.size()); i++) { 
    if(!('0' <= s[i] && s[i] <= '9')) continue; 
    if(s[i] == mx_occ) idxs.push(i); 
    else { 
     if(!idxs.empty()) { 
     int j = idxs.front(); 
     idxs.pop(); 
     swap(s[i], s[j]); 
     idxs.push(i); 
     } 
    } 
    } 
    // instead of the below while loop 
    // you can loop on the queue and 
    // erase the chars at the positions in that queue. 

    int i = int(s.size()) - 1; 
    while(i >= 0 && (!('0' <= s[i] && s[i] <= '9') || s[i] == mx_occ)) { 
    --i; 
    } 
    if(i >= 0) s = s.substr(0, i + 1); 
    else s = ""; 
    cout << s << "\n"; 
} 
0

string newString = "1 0 3 0 4 0 7 0"; 

您可以使用REPLACE語句(使用一個函數,會發現最常見的發生於你,如果你想)

newString = newString.replace(" 0", " "); 

如果你想用一個函數來告訴你哪個字符是最常見的,那麼你將能夠把它放入替換函數的第一個參數。

讓我知道這是否有幫助!

+0

謝謝您的快速回復!我其實已經想通了 - 我實現了我的功能來查找最經常出現的角色,但現在我又遇到了另一個問題:我忘記提及我的行可能是這樣的: – JavaNewb