How to find the last word in a string

  • A+
Category:Languages

I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.

I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:

    String strSpace=" ";     int Temp; //the index of the last space     for(int i=str.length()-1; i>0; i--){         if(strSpace.indexOf(str.charAt(i))>=0){             //some code in between that I not sure how to write         }     } } 

I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!

 


You can do this:

String[] words = originalStr.split(" ");  // uses an array String lastWord = words[words.length - 1]; 

and you've got your last word.

You are splitting the original string at every space and storing the substrings in an array using the String#split method.

Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: