C Program to Find the First Repeated Character in a String

In this post, you will learn how to create a program that displays the first character to be repeated in a string. 

For example, if you enter the string racecar, the program should give the output as The first repetitive character in the string racecar is c. The program should display No character is repeated in the string if a string with no repetitive characters is entered.

Finding the occurrence of the first repetitive character in a string

Let's create a file named repetitive.c and add the following source code to it.

#include<stdio.h>   
# include<string.h> 

int ifexists(char u, char z[],  int v)
{
	int i;
	for (i=0; i<v;i++)
		if (z[i]==u) return (1);
	return (0);
}

void main()
{
	char str1[80],str2[80];
	int n,i,x;
	printf("Enter a string: ");
	scanf("%s",str1);
	n=strlen(str1);
	str2[0]=str1[0];
	x=1; 
	for(i=1;i < n;  i++)
	{
		if(ifexists(str1[i], str2, x))
		{
			printf("The first repetitive character in %s is %c", str1, str1[i]);
			break;
		}
		else
		{
			str2[x]=str1[i];
			x++;
		}
	}
	if(i==n)
		printf("There is no repetitve character in the string %s", str1);
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

Enter a string: sourcecodeexamples
The first repetitive character in sourcecodeexamples is c

Comments