I am supposed to get the first and the last word from a string that is input by a user but im not sure how. Any tips would be great!

//Print the first word and last word from a string

      int index = inputString.indexOf(" ");
      String fistString = inputString.substring(0, index);
      System.out.println("First Word = "+fistString);

Thats what I have to get the first word. It works but i feel like there is an easier way.

4 Years
Discussion Span
Last Post by stultuske

take a look at the split() method in the String class. Using that and a little knowledge about arrays the solution becomes trivial.

Votes + Comments
my thought exactly

I dont think we are supposed to be using arrays. Is there a way with the indexOf method


you can figure out the first word relatively easily using a "compare character read with ascii value of space " strategy. The last word would be a bit tricky. Keep a variable that points to the last position at which a delimiter was read , now while reading a character at a time , if you meet the end of the string , take a substring from that last delim index to String.length - 1 . I havent tested this , but it should get you started.


There is a String method lastIndexOf() which easily allows to get the last word of a string, for example (assuming separator ' '):

     String s = "Able was I ere I saw Elba";
     System.out.println("Last word: " 
     + s.substring (s.lastIndexOf (' '), s.length())); // Elba

There will be an exception if separator is not contained in the string, so lastIndexOf() should be checked whether it is -1.

Edited by 1stDAN


unless your assignment explicitly states you can't use something, you can use it.
Your teacher may not like to see solutions that differ from what he had in mind, but any decent teacher will accept them if they're valid solutions (and especially if they're more efficient than what he had in mind).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.