Q:

Write a Scala program to count and print all the duplicates in the input string

0

Write a Scala program to count and print all the duplicates in the input string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

object Scala_String {

  def showDuplicates(str1: String): Unit = {
    val MAX_CHARS = 256;
    val ctr = new Array[Int](MAX_CHARS);
    for (i <- 0 to str1.length - 1)
      ctr(str1.charAt(i)) = ctr(str1.charAt(i)) + 1;
    for (i <- 0 to MAX_CHARS - 1)
      if (ctr(i) > 1)
        printf("%c  appears  %d  times\n", i, ctr(i));
  }

  def main(args: Array[String]): Unit = {
    val str1 = "w3resource";
    println("The given string is: " + str1);
    println("The duplicate characters and counts are: ");
    showDuplicates(str1);
    val str2 = "The Scala Programming Language";
    println("The given string is: " + str2);
    println("The duplicate characters and counts are: ");
    showDuplicates(str2);
  }
}

Sample Output:

The given string is: w3resource
The duplicate characters and counts are: 
e  appears  2  times
r  appears  2  times
The given string is: The Scala Programming Language
The duplicate characters and counts are: 
   appears  3  times
a  appears  5  times
e  appears  2  times
g  appears  4  times
m  appears  2  times
n  appears  2  times
r  appears  2  times

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now