Open In App

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

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

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

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.

Syntax:

str.substring(startIndex: Int, endIndex: Int)

Example:

Scala
def removeFirstAndLast(str: String): String = {
  str.substring(1, str.length - 1)
}

// Example usage:
val originalString = "GeeksForGeeks"
val modifiedString = removeFirstAndLast(originalString)
println(modifiedString)

Output

eeksForGeek

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.

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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads