C Programming: Find the repeated character in a given string
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
}
Sample Output:
Input a string: The first repetitive character in w3resource is: r
Flowchart :
C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to split string by space into words.
Next: Write a C programming to count of each character in a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics