开发者

How to display duplicate characters in the string?

开发者 https://www.devze.com 2023-04-13 07:49 出处:网络
I have writ开发者_开发百科ten a program to display the duplicate character(s) in a string, but it displays the characters again if it comes more than 2 times. Any solution to find it exactly?

I have writ开发者_开发百科ten a program to display the duplicate character(s) in a string, but it displays the characters again if it comes more than 2 times. Any solution to find it exactly?

//to find duplicate characters in the string........

#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]!='\0';i++)
    {
        for(j=i+1;ar[j]!='\0';j++)
        {
            if(ar[i]==ar[j])
            {  
                cout<<ar[i]<<endl;
                break;
            }
        }
    }

    system("pause");
    return 0;
}


Another method is to sort the characters in the string, then examine the sorted string.

Duplicate characters will be easy to find, since they will be next to each other.


You should keep track of how many times each character appears:

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]!='\0';i++)
{
    count[ar[i]] = count[ar[i]] + 1;

    // now you can check if count is 1, and if so then do whatever
}


here is the sample code to find duplicate chars in a string. Complete code will be available at 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));
        }
    }
}

    


I hope this would help:

#include <iostream>
using namespace std;

int main() {
    char str[50];
    cout << "Enter a string" << endl;
    gets(str);

    for(int i=0; str[i]!='\0'; i++)
    {
        for(int j=i+1; str[j]!='\0'; 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] != '\0'; 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;
}


Below is the code works for [a-z] but it's very space efficient. Because it's using just two integers to find the solution. thanks.

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));
    }
}


Here is the working code from 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; 
} 


If you want to maintain the order, you can try out my code below. I have only made it for lower case tho.

The trick is to keep count of the frequency of each character and checking it each time during the loop.

#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] != '\0'; ++i)
        {
            hsn[str[i]] += 1;
        }
        
        for(int i = 0; i < N; ++i)
        {
            if(hsn[i] > 1)
            {
                cout << (char)i << "  "  << hsn[i] << endl;
            }
        }
    }
    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号