'lstrip and rstrip non blank character from string
How do you strip characters (not necessarily white space i.e. blanks) from the start and end of a String in Scala?
The Python analogue to what I am looking for is lstrip
and rstrip
.
This is the desired functionality:
ltrim("{blah blah}", "{") should equal("blah blah}")
ltrim("blah blah", "{") should equal("blah blah") // no exception
rtrim("blah blah}", "}") should equal("blah blah")
Solution 1:[1]
You could use dropWhile
if you want to remove a specific character from the beginning of a String
:
"{{blah blah}".dropWhile(_ == '{')
// "blah blah}"
This drops any character from the left of the String
which fulfills the given predicate which in this case is being equal to the character to remove.
In order to remove a character from the right, since there is not yet a dropWhileRight
equivalent in the standard library, one way could consist in a double reverse:
"{{blah blah}".reverse.dropWhile(_ == '}').reverse
// {{blah blah
or slightly more efficients:
"{{blah blah}}".dropRight("{{blah blah}}".reverse.segmentLength(_ == '}'))
// {{blah blah
"{{blah blah}}".stripSuffix("{{blah blah}}".reverse.takeWhile(_ == '}'))
// {{blah blah
Solution 2:[2]
Use regular expressions functions
scala> "{blah blah}".replaceAll("""^[{]+""","")
res35: String = blah blah}
scala> "{{blah blah}".replaceAll("""^[{]+""","")
res36: String = blah blah}
scala> "blah blah}".replaceAll("""^[{]+""","")
res37: String = blah blah}
scala> "blah blah}".replaceAll("""[}]+$""","")
res38: String = blah blah
scala>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |