Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++, write a function to find duplicate characters in a string. If a duplicat

ID: 3763027 • Letter: I

Question

In C++, 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 fucntion 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 as 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

#include <iostream>

using namespace std;

int detectDuplicate(string str) {

for (int i=0; i<str.length(); i++) {

for (int j=i+1; j<str.length(); j++) {

if (tolower(str[i]) == tolower(str[j])) {

return i;

}

}

}

return -1;

}

int main() {

string str;

cout<<"Enter a string: ";

cin>>str;

  

int dup=detectDuplicate(str);

if(dup != -1) {

cout<<str<<" has duplicate element in position "<<dup+1<<" which is "<<str[dup];

} else {

cout<<"No duplicate element in string "<<str;

}

cout<<" ";

return 0;

}