HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

A scala implementation of the Java trim method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
trimthemethodjavascalaimplementation

Problem

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  0) || (len < count)) ? substring(st, len) : this;
}


My Scala version iterates over a string, and when it encounters a space char, the tail of the string is returned. The entire string is then reversed, so it can access the trailing whitespace. This new string is iterated over until a space char is encountered 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? Does it seem wasteful reversing the string twice?

Solution

No good idea about the concern of reversing the list twice. But you may

-
Let you inner function return a List instead of a string thus having less conversions from list to string and string to list.

-
Change your match to the following pattern (not tested):

case " " :: tail => removePreString(tail)
case _ => _


I just realize you could also use on a list def dropWhile(p: (A) ⇒ Boolean): List[A] which drops longest prefix of elements that satisfy a predicate. You could then chain dropWhile not a space | reverse | dropwhile not a space | reverse...

Code Snippets

case " " :: tail => removePreString(tail)
case _ => _

Context

StackExchange Code Review Q#20452, answer score: 3

Revisions (0)

No revisions yet.