How to use drop and dropRight methods In Scala

In this approach we are using drop and dropRight method. drop method is used to remove first n elements from the collection and dropRight removes the last n elements. By calling drop(1) and dropRight(1) on the string, we remove the first and last characters, respectively.

Syntax:

str.drop(1).dropRight(1)

Example:

Scala
def removeFirstAndLast(str: String): String = {
  str.drop(1).dropRight(1)
}

// Example usage:
val originalString = "Welcome to GFG"
val modifiedString = removeFirstAndLast(originalString)
println(modifiedString)

Output

elcome to GF

How to remove First and Last character from String in Scala?

In this article, we will explore different approaches to removing the first and last character from a string in Scala.

Table of Content

  • Using substring method
  • Using drop and dropRight methods

Similar Reads

Using substring method

In this approach, we are using the substring method which takes two arguments the starting index and the ending index. By passing 1 as the starting index and str.length – 1 as the ending index, we can remove the first and last characters from the string....

Using drop and dropRight methods

In this approach we are using drop and dropRight method. drop method is used to remove first n elements from the collection and dropRight removes the last n elements. By calling drop(1) and dropRight(1) on the string, we remove the first and last characters, respectively....

Contact Us