How do I trim the starting and ending character of a string in Scala
For inputs such as ",hello"
or "hello,"
, I need the output as "hello"
.
Is there is any built-in method to do this in Scala?
What is trim() in Scala? The trim() method is used to remove all the leading and trailing spaces that are present in the string. For example, if the string looks like, " Hello World " then there is a lot of empty space before the term “Hello” and after the term “World”. The method trim() is used to remove these spaces.
Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.
stripMargin ( '#' ) All of these approaches yield the same result, a multiline string with each line of the string left justified: Four score and seven years ago. This results in a true multiline string, with a hidden \n character after the word “and” in the first line.
Use the split() Method to Split a String in Scala Scala provides a method called split() , which is used to split a given string into an array of strings using the delimiter passed as a parameter. This is optional, but we can also limit the total number of elements of the resultant array using the limit parameter.
Try
val str = " foo " str.trim
and have a look at the documentation. If you need to get rid of the ,
character, too, you could try something like:
str.stripPrefix(",").stripSuffix(",").trim
Another way to clean up the front-end of the string would be
val ignoreable = ", \t\r\n" str.dropWhile(c => ignorable.indexOf(c) >= 0)
which would also take care of strings like ",,, ,,hello"
And for good measure, here's a tiny function, which does it all in one sweep from left to right through the string:
def stripAll(s: String, bad: String): String = { @scala.annotation.tailrec def start(n: Int): String = if (n == s.length) "" else if (bad.indexOf(s.charAt(n)) < 0) end(n, s.length) else start(1 + n) @scala.annotation.tailrec def end(a: Int, n: Int): String = if (n <= a) s.substring(a, n) else if (bad.indexOf(s.charAt(n - 1)) < 0) s.substring(a, n) else end(a, n - 1) start(0) }
Use like
stripAll(stringToCleanUp, charactersToRemove)
e.g.,
stripAll(" , , , hello , ,,,, ", " ,") => "hello"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With