w3resource

C Programming: Find the repeated character in a given string


32. Find Repeated Character

Write a C program to find the repeated character in a string.

Sample Solution:

C Code:

// Including the standard I/O library
#include<stdio.h>
#include<string.h>
// Function to check if a character exists in a string
int ifexists(char p, char q[], int v) {
    int i;
    for (i = 0; i < v; i++)
        if (q[i] == p) return (1); // If character exists, return 1
    return (0); // If character doesn't exist, return 0
}
int main() {
    char string1[80], string2[80]; // Declaration of string arrays
    int n, i, x; // Integer variables for iteration and length
    printf("Input a string: ");
    scanf("%s", string1); // Taking input string from the user
    n = strlen(string1); // Finding the length of the input string
    string2[0] = string1[0]; // Storing the first character of the input string in a new string array
    x = 1; // Initializing index for the new string as 1
    for (i = 1; i < n; i++) { // Loop through each character of the input string starting from index 1
        if (ifexists(string1[i], string2, x)) { // Check if the character exists in the new string
            printf("The first repetitive character in %s is: %c ", string1, string1[i]); // Print the first repetitive character
            break; // Exit the loop
        } else {
            string2[x] = string1[i]; // Add the character to the new string array
            x++; // Increment the index of the new string array
        }
    }
    if (i == n)
        printf("There is no repetitive character in the string %s.", string1); // If no repetitive character found in the input string
}

Output:

 Input a string: The first repetitive character in w3resource is: r 

Flowchart:

Flowchart: Find the repeated characte in a given string


For more Practice: Solve these Related Problems:

  • Write a C program to detect and print the first repeated character in a string using nested loops.
  • Write a C program to find all characters that occur more than once in a string and display their positions.
  • Write a C program to determine the first character that repeats in a string by comparing each character with the rest.
  • Write a C program to identify repeated characters and print each with the number of times it appears.

Go to:


PREV : Split String by Spaces.
NEXT : Count Each Character Occurrence.

C Programming Code Editor:



Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.