Let's assume that we have defined a string, str1, of some length, and have entered the following characters—racecar.
Each of the characters of the string racecar will be assigned to the respective index locations of str1, that is, r will be assigned to str1[0], a will be assigned to str1[1], and so on. Because every string in C is terminated by a null character, \0, the last index location of str1 will have the null character \0, as follows:
Using the library function strlen, the length of str1 is computed and a for loop is used to access all of the characters of str1, one by one, except for the first character. The first character is already assigned to str2, as shown in the following diagram:
Each character that is accessed from str1 is passed through the ifexists function. The ifexists function will check whether the supplied character already exists in str2 and will return a Boolean value accordingly. The function returns 1, that is, true, if the supplied character is found in str2. The function returns 0, that is, false, if the supplied character is not found in str2.
If ifexists returns 1, this means that the character is found in str2, and hence, the first repetitive character of the string is displayed on the screen. If the ifexists function returns 0, this means that the character does not exist in str2, so it is simply added to str2 instead.
Since the first character is already assigned, the second character of str1 is picked up and checked to see if it already exists in str2. Because the second character of str1 does not exist in str2, it is added to the latter string, as follows:
The procedure is repeated until all of the characters of str1 are accessed. If all the characters of str1 are accessed and none of them are found to exist in str2, this means that all of the characters in str1 are unique and none of them are repeated.
The following diagram shows strings str1 and str2 after accessing the first four characters of str1. You can see that the four characters are added to str2, since none of them already exist in str2:
The next character to be accessed from str1 is c. Before adding it to str2, it is compared with all the existing characters of str2 to determine if it already exists there. Because the c character already exists in str2, it is not added to str2 and is declared as the first repeating character in str1, as follows:
Let's use GCC to compile the repetitive.c program, as follows:
D:\CBook>gcc repetitive.c -o repetitive
Let's run the generated executable file, repetitive.exe, to see the output of the program:
D:\CBook>./repetitive
Enter a string: education
There is no repetitive character in the string education
Let's run the program again:
D:\CBook>repetitive
Enter a string: racecar
The first repetitive character in racecar is c
Voilà! We've successfully found the first repeating character in a string.
Now, let's move on to the next recipe!