Java: how to return string before char

I have the following string

String name = "John - Paul"

So what i want to do is retrieve John (all before the -). This is what i am trying but i cannot retrieve from before the - only after

String parseName = name.substring(name.indexOf(" - ", -1), name.indexOf(" - ", 0));

How do you do this and can someone explain as well please (note: i do not want to use regex)?

Answers


You are mixing your starting and ending indices - you need to take a substring from the first character (index=0) up to the index of " - " :

String parseName = name.substring(0, name.indexOf(" - "));

Need Your Help

MySQL not updating on duplicate key

mysql indexing duplicates unique

Hi, I'm having trouble with this query: