Re-Implement the String Split Function In Java

in #programming5 years ago

In Java, we can use the handy String's method Split to split a string by the given delimiter into array of strings. Have you wondered how it is implemented? See below String Split function from JDK:

public class StringUtils {
    public static String[] split(String input, char delimiter) {
        var v = new Vector();
        boolean moreTokens = true;

        while (moreTokens) {
            int tokenLocation = input.indexOf(delimiter);
            if (tokenLocation > 0) {
                var subString = input.substring(0, tokenLocation);
                v.addElement(subString);
                input = input.substring(tokenLocation + 1);
            } else {
                moreTokens = false;
                v.addElement(input);
            }
        }

        var res = new String[v.size()];

        for (int i = 0; i != res.length; ++i) {
            res[i] = (String)v.elementAt(i);
        }

        return res;
    }
}

We repeatedly search for the delimiter using indexOf function, then push a substring to the vector, and keep doing this until no more token. Then, we convert the vector of tokens into an array.

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Hello Sir, @justyy today I missed your upvote. I'm an active delegator of you. plz check-

https://steemit.com/hive-129948/@rme/phishing-attack-on-steemit-do-not-fall-into-the-trap

you're awesome. thanks:)

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60159.19
ETH 1576.47
USDT 1.00
SBD 0.42