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
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:
def removeFirstAndLast(str: String): String = {
str.substring(1, str.length - 1)
}
// Example usage:
val originalString = "w3wiki"
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:
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
Contact Us