Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Duplicate Characters in a String

This article explains how to find duplicate characters in a string using various programming languages. A duplicate character is any character that appears more than once in a string. We'll walk through implementations in C, C++, Python, and Java.

(a.) C Code

#include <stdio.h>

int main() {
    char str[] = "programming";
    int count[256] = {0};

    for (int i = 0; str[i] != '\0'; i++) {
        count[(unsigned char)str[i]]++;
    }

    printf("Duplicate characters in the string:\n");
    for (int i = 0; i < 256; i++) {
        if (count[i] > 1) {
            printf("Character '%c' occurs %d times\n", i, count[i]);
        }
    }

    return 0;
}
Output:
Enter a string: programming
Character 'g' occurs 2 times
Character 'r' occurs 2 times

(b.) C++ Code

#include <iostream>
using namespace std;

int main() {
    string str = "programming";
    int count[256] = {0};

    for (int i = 0; i < str.length(); i++) {
        count[(unsigned char)str[i]]++;
    }

    cout << "Duplicate characters in the string:" << endl;
    for (int i = 0; i < 256; i++) {
        if (count[i] > 1) {
            cout << "Character '" << (char)i << "' occurs " << count[i] << " times" << endl;
        }
    }

    return 0;
}
Output:
Enter a string: programming
Character 'g' occurs 2 times
Character 'r' occurs 2 times

(c.) Python Code

def find_duplicates(s):
    count = {}
    for char in s:
        count[char] = count.get(char, 0) + 1

    print("Duplicate characters in the string:")
    for char, freq in count.items():
        if freq > 1:
            print(f"Character '{char}' occurs {freq} times")

s = "programming"
find_duplicates(s)
Output:
Enter a string: programming
Character 'g' occurs 2 times
Character 'r' occurs 2 times

(d.) Java Code

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> count = new HashMap<>();

        for (char c : str.toCharArray()) {
            count.put(c, count.getOrDefault(c, 0) + 1);
        }

        System.out.println("Duplicate characters in the string:");
        for (Map.Entry<Character, Integer> entry : count.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("Character '" + entry.getKey() + "' occurs " + entry.getValue() + " times");
            }
        }
    }
}
Output:
Enter a string: programming
Character 'g' occurs 2 times
Character 'r' occurs 2 times

How did you feel about this post?

😍 🙂 😐 😕 😡

Was this helpful?

👍 👎