2016-11-09 84 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