Martin Erlic
Martin Erlic

Reputation: 5667

Use substring to retain middle value in string

String s = "John Stuart Mill";
String aFriendlyAssigneeName = s.substring(s.lastIndexOf('-')+1);

I'm currently able to remove jstm - from jstm - John Stuart Mill but I'm not sure how to now remove everything after John.

All data will be in the format initials - Fist Middle Last. Basically I just want to strip everything except First.

How can I accomplish this? Perhaps by removing everything after the third white space...

Upvotes: 0

Views: 860

Answers (5)

m0skit0
m0skit0

Reputation: 25874

In my opinion this is a job for a regex: .* - (\w+)? .*

final String value = "jstm - John Stuart Mill";
final Matcher matcher = Pattern.compile(".* - (\\w+)? .*").matcher(value);
matcher.matches();
System.out.println(matcher.group(1));

In my opinion using a regex vs substring:

Pros:

  • More clear on what you expect as input and what you intent to capture.
  • Easily modified/extended if input changes or you want to capture some other part.

Cons:

  • Regexes can look more cryptic to someone that's not used to them.

Upvotes: 1

Dorukhan Arslan
Dorukhan Arslan

Reputation: 2754

Why do not you find the substring after the first occurrence of the space in the string that you found without initials?

aFriendlyAssigneeName = aFriendlyAssigneeName.substring(aFriendlyAssigneeName.indexOf('  '));

Upvotes: 2

Reg
Reg

Reputation: 11245

You are looking for the following method -

s.substring(startIndex, endIndex);

This gives a begin and end index, this will help you to easily get the middle of any String.

You can then find the last index with a bit of ( I dare say ) magic...

endIndex = indexOf(" ", fromIndex)

Where from index is

s.lastIndexOf('-')+1

Alternatively

If substring is no "hard" requirement, try using

String[] words = s.split(" ");

This will return an array of all values separated by the space.

You can then just select the index of the word. ( This case words[2] )

Upvotes: 2

zsmb13
zsmb13

Reputation: 89608

I'd just use this, should be fast enough, and quite short:

String aFriendlyAssigneeName = s.split(" ")[2];

(Splits the string at the spaces in it, and takes the third member of the array, which should be the first name if they're all in that format.)

Upvotes: 3

Jens
Jens

Reputation: 69470

This should work:

String s = "jstm - John Stuart Mill";
String aFriendlyAssigneeName = s.substring(s.lastIndexOf('-')+1);
String aFriendlyAssigneeName = aFriendlyAssigneeName.substring(aFriendlyAssigneeName.indexOf(' '));

After you have removed th Initials, the firstname ends after the first blank.

Upvotes: 2

Related Questions