I'm a scala beginner and looking at the trim() method of the java api I noticed side effects, so I attempted to implement a functional version in scala.
Here is the java version :
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
My scala version iterates over a string & when it encounters a space char the tail of the string is returned. The entire string is then reversed, so can access the trailing whitespace. This new string is iterated over until a space char is encounterd and the tail of this string is returned. This new string is then reversed again to maintain the original string order :
def trim(stringToTrim : String) : String = {
def removePreString[String](list : List[String]) : java.lang.String = list match {
case head :: tail => {
if(head.toString.equals(" ")){
removePreString(tail)
}
else {
head.toString + tail.mkString
}
}
}//end removePreString
val preString = removePreString(stringToTrim.toList)
val reveresedString = preString.toList.reverse
val reveresedPostString = removePreString(reveresedString)
reveresedPostString.reverse
}//end trim
How can this code be improved ? It seems wasteful reversing the string twice ?