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

Write a function to find duplicate characters in a string, if a duplicate is fou

ID: 3762809 • 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. You 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

#include <stdio.h>
int main(){
   char c[1000],ch;
   int i,count=0;
   printf("Enter a string: ");
   gets(c);
   printf("Enter a character to find frequency: ");
   scanf("%c",&ch);
   for(i=0;c[i]!='';++i)
   {
       if(ch==c[i])
           ++count;
   }
   printf("Frequency of %c = %d", ch, count);
   return 0;
}

java code

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharsInString {

    public void findDuplicateChars(String str){
        
        Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
        char[] chrs = str.toCharArray();
        for(Character ch:chrs){
            if(dupMap.containsKey(ch)){
                dupMap.put(ch, dupMap.get(ch)+1);
            } else {
                dupMap.put(ch, 1);
            }
        }
        Set<Character> keys = dupMap.keySet();
        for(Character ch:keys){
            if(dupMap.get(ch) > 1){
                System.out.println(ch+"--->"+dupMap.get(ch));
            }
        }
    }
    
    public static void main(String a[]){
        DuplicateCharsInString dcs = new DuplicateCharsInString();
        dcs.findDuplicateChars("Java2Novice");
    }
}
- See more at: http://java2novice.com/java-interview-programs/duplicate-string-character-count/#sthash.YKJEGoNw.dpuf

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote