Write a function to find duplicate characters in a string, if a duplicate is fou
ID: 3763729 • Letter: W
Question
Write a function to find duplicate characters in a string, if a duplicate is found, then break out of the search loop in the function and print the position of the detected duplicate character.
Your program must do the following:
1. in main function declare and input a string
2. call a function called detectDuplicate with the input string as argument
3. detectDuplicate function must look for a duplicate character and return the value of the duplicate position to the main function
Note:The loop should be broken when the first duplicate is found
Example: Hello should return 3 as the duplicate of l is found at position 3 Congratulations should return 9 as the duplicate of a is found at position 9. Even though o is repeated and o occurs before a in the string, the duplicate of a is found first and so it must break out and return this value.
Explanation / Answer
I have written this below program for to find the first index position of dupliacte charecter in the gven string as a function return value.. see the below code for find the inndex value of first dupliacte occurrence in the given string..
# include <stdio.h>
/* Return the first Index of duplicates character present in the given string */
int detectDuplicate(char *str)
{
int i,j, index;
for(i = 0; str[i] != '';i++)
{
for(j = 1; str[j] != '';j++)
{
if(str[i] == str[j])
{
index = i;
break;
}
}
}
return index;
}
int main()
{
int i, size, index;
char str[] = "hello";
size = strlen(str);
index = detectDuplicate(str);
printf("Index Position is: %d ", index);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.