user3678006
user3678006

Reputation: 39

How to tokenize a string using indexOf and substring methods

So I have to tokenize a string, and I can only use these 2 methods to tokenize I have the base, but I don't know what to put in, My friend did it, but I forgot how it looked, it went something like this I remember he split it using the length of a tab

public class Tester
{
private static StringBuffer sb = new StringBuffer ("The cat in the hat");
public static void main(String[] args) 
{
    for(int i = 0; i < sb.length() ; i++)
    {
        int tempIndex = sb.indexOf(" ", 0);
        sb.substring(0,tempIndex);
        if(tempIndex > 0) 
        {
            System.out.println(sb.substring(0,tempIndex));
            sb.delete(0, sb.length());
        }

    }

}
}

Upvotes: 0

Views: 919

Answers (2)

Levenal
Levenal

Reputation: 3806

If your are familiar with a while loop construct you can take a look at my pseudocode, should be within the constraints of your problem:

String text = "texty text text"

while(TextHasASapce){
     print text up to space
     set text to equal all text AFTER the space 
}
print ??

Using your two allowed methods the above is convertible line by line to what you are after.

Hope it helps.

Upvotes: 1

Anubian Noob
Anubian Noob

Reputation: 13596

String.indexOf(int ch) returns the index of a character. If you do sb.indexOf(' ') you'll get the first index of a space. You can use that in conjunction with substring(): sb.substring(0,sb.indexOf(' ')-1) will get you your first token.

This seems like a homework problem, so I don't want to give you the full answer, but you probably can work it out. Comment if you need more help.

Upvotes: 1

Related Questions