user3930280
user3930280

Reputation: 21

Returning the nth Token

I'm very new at Java and I have a question about a summer assignment. These are the instructions:

Write a class called SpecialToken that has a static method called thirdToken. This

method should return as a String, the third token of a String that you pass as a parameter.

You may assume that spaces will serve as delimiters.

This is what I have so far but honestly I am stumped at what the parameter should be and how to return the third token! I was thinking I could do something like nextToken() until the third.

public class SpecialToken {
    public static String thirdToken() {

    }
}

Upvotes: 2

Views: 3489

Answers (1)

19greg96
19greg96

Reputation: 2591

Try something like

public class SpecialToken {
    public static String thirdToken(String str) {
        String[] splited = str.split(" ");
        return splited[2];
    }
}

Also see this tutorial or try searching google for "java split string into array by space"

Also note, as Betlista said this does not have any error checking, so if the passed string only has two tokens delimited by one space, you will get an Array out of bounds exception.

Or an other way would be to "Use StringTokenizer to tokenize the string. Import java.util.StringTokenizer. Then create a new instance of a StringTokenizer with the string to tokenize and the delimiter as parameters. If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space. After you have the StringTokenizer, you can use the nextToken() method to get each token. " via Wikihow

With this method, your code should look something like this:

public class SpecialToken {
    public static String thirdToken(String str) {
        StringTokenizer tok = new StringTokenizer(str); // If you do not enter the delimiter as a parameter, the delimiter will automatically default to white space
        int n = tok.countTokens();
        if (n < 3) {return "";}
        tok.nextToken();
        tok.nextToken();
        return tok.nextToken();
    }
}

However keep in mind Wikihow's warning "now, the use of StringTokenizer is discouraged and the use of the split() method in the String class or the use of the java.util.regex package is encouraged."

Upvotes: 4

Related Questions