w3resource

Scala Programming: Count and print all the duplicates in the input string


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

Sample Solution:

Scala Code:

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

Go to:


PREV : Write a Scala program to reverse every word in a given string.
NEXT : Write a Scala program to check if two given strings are rotations of each other.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.