Open In App

How to Remove Double Quotes from String in Scala?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This article focuses on discussing how to remove double quotes from a string in Scala. Removing double quotes consists of eliminating all occurrences of double quotes (“) from a given string, resulting in a modified string without the double quotes.

Remove Double Quotes from String in Scala

Below are the possible approaches to remove double quotes from strings in Scala.

Approach 1: Using Replace Method

  1. In this approach, we are using the replace method in Scala, which takes two parameters: the substring to be replaced (in this case, the double quote \”) and the replacement string (an empty string “”).
  2. This method removes all occurrences of the specified substring from the input string, effectively removing double quotes from the given string inputString.

In the below example, the replace Method is used to remove double quotes from a string.

Scala
// Creating Object
object GFG {

  // Main Method 
  def main(args: Array[String]): Unit = {
    // Input string with double quotes
    val inputString = "\"Hello, GeeksforGeeks!\""

    // Removing double quotes using replace method
    val outputString = inputString.replace("\"", "")

    // Printing the result
    println("Original String: " + inputString)
    println("String without double quotes: " + outputString)
  }
}

Output:

Screenshot-2024-03-27-at-14-49-07-Scastie---An-interactive-playground-for-Scala

Approach 2: Using Filter Method with Lambda Function

  1. In this approach, we are using the filter method with a lambda function (_ != ‘\”‘) to remove double quotes from the input string.
  2. The lambda function checks each character in the string and keeps only those characters that are not equal to the double quote “\”.
  3. The output outputString contains the original string without any double quotes.

In the below example, the filter Method with Lambda Function is used to remove double quotes from a string.

Scala
// Creating Object
object GFG {

  // Main Method
  def main(args: Array[String]): Unit = {
    // Input string with double quotes
    val inputString = "\"Hello, GFG!\""

    // Removing double quotes using filter method with lambda function
    val outputString = inputString.filter(_ != '\"')

    // Printing the result
    println("Original String: " + inputString)
    println("String without double quotes: " + outputString)
  }
}

Output:

Screenshot-2024-03-27-at-14-51-37-Scastie---An-interactive-playground-for-Scala


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads