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:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.