w3resource

Scala Programming: Print after removing duplicates from a given string

Scala Programming String Exercise-14 with Solution

Write a Scala program to print after removing duplicates from a given string.

Sample Solution:

Scala Code:

object Scala_String {

  def removeDuplicateChars(s: String): String = {
    val arr1 = s.toCharArray();
    var targetStr = "";
    for (value <- s) {
      if (targetStr.indexOf(value) == -1) {
        targetStr += value;
      }
    }
    return targetStr;
  }

  def main(args: Array[String]): Unit = {
    var str1 = "w3resource";
    println("The given string is: " + str1);
    System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1)
    );
    str1 = "Scala";
    println("The given string is: " + str1);
    System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1)
    );
    str1 = "2q34u923u4928402";
    println("The given string is: " + str1);
    System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1)
    );
  }
}

Sample Output:

The given string is: w3resource
After removing duplicates characters the new string is: w3resouc
The given string is: Scala
After removing duplicates characters the new string is: Scal
The given string is: 2q34u923u4928402
After removing duplicates characters the new string is: 2q34u980

Scala Code Editor :

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

Previous:Write a Scala program to trim any leading or trailing whitespace from a given string.
Next:Write a Scala program to find the maximum occurring character in a string.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.