如何在字符串中显示重复字符

How to display duplicate characters in the string?

本文关键字:字符 显示 字符串      更新时间:2023-10-16

我写了一个程序来显示字符串中重复的字符,但是如果它出现超过2次,它会再次显示这些字符。有办法精确地找到它吗?

//查找字符串中重复的字符........

#include<iostream>
using namespace std;
int main()
{
    int i,j;
    char ar[100];
    cout<<"enter string:";
    cin.getline(ar,100);
    for(i=0;ar[i]!='';i++)
    {
        for(j=i+1;ar[j]!='';j++)
        {
            if(ar[i]==ar[j])
            {  
                cout<<ar[i]<<endl;
                break;
            }
        }
    }
    system("pause");
    return 0;
}

另一种方法是对字符串中的字符进行排序,然后检查排序后的字符串。

重复的字符将很容易找到,因为它们将紧挨着彼此。

您应该跟踪每个字符出现的次数:

int count[256]; // <-- assuming char is 8 bytes
for(i=0;i!=256;++i) 
{
    count[i] = 0; // <-- set all counts to be zero
}
for(i=0;ar[i]!='';i++)
{
    count[ar[i]] = count[ar[i]] + 1;
    // now you can check if count is 1, and if so then do whatever
}

下面是在字符串中查找重复字符的示例代码。完整的代码可在http://java2novice.com/java-interview-programs/duplicate-string-character-count/

获得。
public void findDuplicateChars(String str){
    Map<Character, Integer> dupMap = new HashMap<Character, Integer>(); 
    char[] chrs = str.toCharArray();
    for(Character ch:chrs){
        if(dupMap.containsKey(ch)){
            dupMap.put(ch, dupMap.get(ch)+1);
        } else {
            dupMap.put(ch, 1);
        }
    }
    Set<Character> keys = dupMap.keySet();
    for(Character ch:keys){
        if(dupMap.get(ch) > 1){
            System.out.println(ch+"--->"+dupMap.get(ch));
        }
    }
}

我希望这对你有帮助:

#include <iostream>
using namespace std;
int main() {
    char str[50];
    cout << "Enter a string" << endl;
    gets(str);
    for(int i=0; str[i]!=''; i++)
    {
        for(int j=i+1; str[j]!=''; j++)
        {
            if(str[i]==str[j])
            cout << "Character " << str[i] << " is repeated" << endl;
        }
    }

    return 0;
}
C++ solution:
#include <iostream>
#include <set>
using namespace std;
set<char> findDuplicate(string s, int c[])
{
    for (int i = 0; i != 256; i++)
        c[i] = 0;
    set<char> set;
    for (int i = 0; s[i] != ''; i++)
    {
        c[s[i]] = c[s[i]] + 1;
        if (c[s[i]] > 1)
            set.insert(s[i]);
    }
    return set;
}
int main(int argc, char const *argv[])
{
    int c[256];
    string s = "test string";
    set<char> set = findDuplicate(s, c);
    for (auto it = set.begin(); it != set.end(); ++it)
    cout << *it << " ";
    return 0;
}

下面是[a-z]的代码,但它非常节省空间。因为它只用了两个整数来求解。谢谢。

public class AllDuplicatesInString
{
    static class BitSet
    {
        int justPresent, moreThanOnce;
        BitSet() 
        {
            justPresent = moreThanOnce = 0;
        }
        void set(int k)
        {
            if(isSetJustPresent(k))
            {
                k = k - 'a';
                moreThanOnce = moreThanOnce | (1<<k);
                return;
            }
            k = k - 'a';
            justPresent = justPresent | (1<<k);
        }
        boolean isSetJustPresent(int k)
        {
            k = k - 'a';
            return (justPresent & (1<<k))!=0;
        }
        boolean isSetMoreThanOnce(int k)
        {
            k = k - 'a';
            return (moreThanOnce & (1<<k))!=0;
        }
    }
    public static String duplicateChars(String str)
    {
        if(str==null || str.equals("")){
            throw new NullPointerException();
        }
        BitSet b = new BitSet();
        for(int i=0;i<str.length();i++){
            b.set(str.charAt(i));
        }
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<26;i++){
            if(b.isSetMoreThanOnce(i+'a')){
                stringBuilder.append((char)(i+'a'));
            }
        }
        return stringBuilder.toString();
    }
    public static void main(String[] args)
    {
        String str = "aaaabbbbjjjjsfsfzcncnzcmcncmnczmjsdjs";
        System.out.println(duplicateChars(str));
    }
}

下面是GeeksForGeeks的工作代码

// C program to count all duplicates from string using hashing 
# include <stdio.h> 
# include <stdlib.h> 
# define NO_OF_CHARS 256 
/* Fills count array with frequency of characters */
void fillCharCounts(char *str, int *count) 
{ 
   int i; 
   for (i = 0; *(str+i);  i++) 
      count[*(str+i)]++; 
} 
/* Print duplicates present in the passed string */
void printDups(char *str) 
{ 
  // Create an array of size 256 and fill count of every character in it 
  int *count = (int *)calloc(NO_OF_CHARS, sizeof(int)); 
  fillCharCounts(str, count); 
  // Print characters having count more than 0 
  int i; 
  for (i = 0; i < NO_OF_CHARS; i++) 
    if(count[i] > 1) 
        printf("%c,  count = %d n", i,  count[i]); 
  free(count); 
} 
/* Driver program to test to pront printDups*/
int main() 
{ 
    char str[] = "test string"; 
    printDups(str); 
    getchar(); 
    return 0; 
} 

如果您想保持顺序,您可以尝试下面的代码。我只设置了小写字母

技巧在于记录每个字符出现的频率,并在循环过程中每次检查一次。

#include <iostream>
#include <cstring>
using namespace std;
char* print_duplicates(const char str[], int n);
int main(){
    char * actual = new char(20);
    char * dup = new char(20);
    cout << "Enter the string: ";
    cin >> actual;
    int size = strlen(actual);
    dup = print_duplicates(actual,size);
    cout << "The duplicates are: " << dup << endl;
    return 0;
}
char* print_duplicates(const char str[], int n){
    int freq[26]{0}, index{0};
    char* duplicates = new char(20);
    for (int i=0;i<n;++i){
        for (int j=i+1;j<n;j++){
            if (freq[str[i]-'a'] == 0){
                if(str[i]==str[j]){
                    ++freq[str[i]-'a'];
                    duplicates[index++] = str[i];
                }
            }
        }
    }
    return duplicates;
}
/* Duplicates in string */
#include <iostream>
using namespace std;
int main() {
    int t; cin >> t;
    while(t--)
    {
        string str;
        cin >> str;
        int N = 128;
        int hsn[N] = {0};
        for(int i = 0; str[i] != ''; ++i)
        {
            hsn[str[i]] += 1;
        }
        
        for(int i = 0; i < N; ++i)
        {
            if(hsn[i] > 1)
            {
                cout << (char)i << "  "  << hsn[i] << endl;
            }
        }
    }
    return 0;
}