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.

Recommended Answers

All 6 Replies

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

commented: my thought exactly +14

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.

Member Avatar for 1stDAN

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.

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).

not to mention that a solution with less chance of throwing exceptions might also be preferrable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.