Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming strings in Scala

Tags:

string

scala

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?

like image 619
yAsH Avatar asked Aug 01 '13 13:08

yAsH


People also ask

How trim works 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.

What does string's TRIM () method do?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.

What is stripMargin in Scala?

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.

How do you split in Scala?

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.


1 Answers

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" 
like image 98
Dirk Avatar answered Oct 09 '22 21:10

Dirk