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:
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