简体   繁体   中英

How to get last word from the last comma in a string

I want to retrieve last word before the last semi-colon in a sentence, please see the following.

String met = "This is the string with comma numberone; string having second wedaweda; last word";
String laststringa = met.substring(met.lastIndexOf(";")-1);
if(laststringa != null)
{
    System.out.println(laststringa);
}else{
    System.out.println("No Words");
}

I am getting strange Results as

a; last word

in my case, for the above string, i should get wedaweda as last before the last semi-colon.

To split a string you'd do the following. This would return an array with the elements split on the "separator"

string_object.split("separator")

In your case you'd do

met.split(";")

And it would return an array with each part as an element. Select the last element to get what you need.

Actually. You said "wedaweda" should be the last result...? So I assume you mean the last word BEFORE the last semi-colon.

So do do this you'd do the split as previously stated, and then, you'd get the second to last element in the array

String[] array = met.split(";'); // split the entire first sentence on semi-colons
String[] words = array[array.length - 2] .split(" "); // split into specific words by splitting on a blank space
String wordBeforeSemiColon = words[words.length - 1]; // get the word directly before the last semi-colon

I tested this code in my IDE and it works exactly as you want.

That character is a semi-colon (not a comma) and the call to lastIndex() gives you the end of your match, you need a second call to lastIndex() to get the start of your match. Something like,

String met = "This is the string with comma numberone; string having second wedaweda; last word";
int lastIndex = met.lastIndexOf(";");
int prevIndex = met.lastIndexOf(";", lastIndex - 1);
String laststringa = met.substring(prevIndex + 1, lastIndex).trim();
if (laststringa != null) {
    System.out.println(laststringa);
} else {
    System.out.println("No Words");
}

Output is

string having second wedaweda

To then get the last word, you could split on \\\\s+ (a regular expression matching one, or more, white-space characters) like

if (laststringa != null) {
    String[] arr = laststringa.split("\\s+");
    System.out.println(arr[arr.length - 1]);
} else {
    System.out.println("No Words");
}

Which outputs (the requested)

wedaweda

It must be:

String laststringa = met.substring(met.lastIndexOf(";")+1);        
                                                       ^

The Word after means you have to add one to the Position of the last comma.

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