Remove duplicate characters from a String in Scala Using foldLeft Method
This is the another method for removing duplicate characters from a String in Scala.
Below is the code in Scala.
//Creating Object
object Gfg {
// defining removeDuplicates Method
def removeDuplicates(str: String): String = {
// Use foldLeft to iterate through each character of the string
str.foldLeft("") { (acc, char) =>
// If the accumulator already contains the character, return the accumulator
if (acc.contains(char)) acc
// Otherwise, append the character to the accumulator
else acc + char
}
}
// Defining Main Method
def main(args: Array[String]): Unit = {
val inputString = "w3wiki"
val outputString = removeDuplicates(inputString)
println(outputString)
}
}
Output:
Explanation:
- We define a function removeDuplicates that takes a string str as input and returns a string with duplicate characters removed.
- We use foldLeft to iterate over each character in the input string.
- For each character, we check if it already exists in the accumulator string (acc). If it does, we don’t add it to the accumulator. If it doesn’t, we append it to the accumulator.
- Finally, we return the accumulator string, which contains unique characters.
- We will create Main Method , call the function removeDuplicates and Print that return output.
How to remove duplicate characters from a String in Scala?
In this article, we will learn how to remove duplicate characters from a string in Scala using different approaches. First, we will look through the Brute-Force Approach and then use different standard libraries.
Examples:
Input: String = “hello”
Output: heloInput: String = “Geeks”
Output: Geks
Contact Us