简体   繁体   中英

return the first word in any string (Java)

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.

The method has to be a for loop method . I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.

How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!

I have to be able to input any two words as a string

The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.

String words = "One two many lots"; // This will be our input

and then invoke and display the first word returned from the method,

So we need a method that takes a String and returns a String.

// Method that returns the first word
public static String firstWord(String input) {
    return input.split(" ")[0]; // Create array of words and return the 0th word
}

static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.

.split(" ") creates an array of Strings delimited at every space. [0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).

and the method has to be a for loop method

Ah crap, then we have to do it the hard way.

// Method that returns the first word
public static String firstWord(String input) {
    String result = "";  // Return empty string if no space found

    for(int i = 0; i < input.length(); i++)
    {
        if(input.charAt(i) == ' ')
        {
            result = input.substring(0, i);
            break; // because we're done
        }
    }

    return result; 
}

I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.

There it is, using those methods you mentioned and the for loop. What more could you want?

But how can I make it so that no matter what phrase I use for the string, it will always return the first word?

Man you're picky :) OK fine:

// Method that returns the first word
public static String firstWord(String input) {
    String result = input;  // if no space found later, input is the first word

    for(int i = 0; i < input.length(); i++)
    {
        if(input.charAt(i) == ' ')
        {
            result = input.substring(0, i);
            break;
        }
    }

    return result; 
}

Put it all together it looks like this:

public class FirstWord {

    public static void main(String[] args) throws Exception
    {
        String words = "One two many lots"; // This will be our input
        System.out.println(firstWord(words)); 
    }

    // Method that returns the first word
    public static String firstWord(String input) {

        for(int i = 0; i < input.length(); i++)
        {
            if(input.charAt(i) == ' ')
            {
                return input.substring(0, i);
            }
        }

        return input; 
    }    
}

And it prints this:

One

Hey wait, you changed the firstWord method there.

Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally . They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.

And please explain what you do, because this is my first year in a CS class. Thank you!

What do I do? I post awesome! :)

Hope it helps.

String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);

So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.

Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.

Simply do

int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);

Note that this will give an IndexOutOfBoundException if there is no space in the sentence.

An alternative would be

String sentences[] = sentence.split(" ");
String firstWord = sentence[0];

Of if you really need a loop,

String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
    if(sentence.charAt(i) == ' ')
    {
        sentence = firstWord.substring(0, i);
        break;
    }
}

The first word is probably the substring that comes before the first space. So write:

int x = input.indexOf(" ");

But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:

if (x==-1) { x = input.length(); }

Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "" , since there is no first word in that case.

You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.

Eg:

int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);

Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.

String Str = new String("Welcome to Stackoverflow");

System.out.print("Return Value :" );
System.out.println(Str.substring(5) );

System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM