Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to create a program that where you put a string inside double quotes and it passes as a single command line parameter, with only a single space separating the words, without using StringTokenizer. You would enter " $ java Comm "this is a test" " and the output would be:
[this]
[is]
[a]
[test]

What I have tried:

Here's what I have so far, I can get it to print out the first word, but I can't figure out how to get it to print the rest:

Java
public class Comm
{

    public static void main(String argv[])
    {
        if (argv.length != 1)
        {
            System.out.println("usage:  Comm \"STRING IN QUOTES\"");
            System.exit(0);
        }

        String str = argv[0];

        String token;
        int space = str.indexOf(' ');
        int i = 0;

        while(i<argv.length)
        {
            token = str.substring(0, space);
            System.out.println("[" + token + "]");
            i++;
        }


    
    }
}
Posted
Updated 17-Jun-16 6:05am

1 solution

You are starting your substring search from the beginning each time. You also increment i only by one, rather than setting it to the start of the next token each time. Try the following:
Java
String token;
int space = 1; // just to satisfy the while clause first time
int i = 0; // start first search at the beginning

while(space > 0)
{
    space = str.indexOf(' ', i); // find the start of the next token
    if (space > 0) // if we found a space
        token = str.substring(i, space); // extract the number of characters
    else
        token = str.substring(i); // end of argv so we just need the offset
    System.out.println("[" + token + "]");
    i = space + 1; // start indexof from the next token
}
 
Share this answer
 
Comments
Member 12589834 17-Jun-16 12:31pm    
Thank you for the explanations, I really appreciate it!
Richard MacCutchan 17-Jun-16 12:59pm    
You're welcome. It's not a perfect solution but should give you some ideas to try a few more things yourself.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900