Sean O'Riordan
Sean O'Riordan

Reputation: 51

How to make a subString from another string by searching for certain characters

String x = "ID:12 Patient Name:...";    
String z = = x.substring(3, x.indexOf(' P'));

I want to get the ID number

Upvotes: 1

Views: 104

Answers (1)

Rahul
Rahul

Reputation: 45070

You're almost there. Just use something like this:-

String z = x.substring(x.indexOf("ID:")+3, x.indexOf("Patient")-1);

+3 - Because you don't need the ID:

-1 - Because you don't need the space before the Patient

This is taking into account that there is a SINGLE space before Patient, if not, as @BuhakeSindi suggested use the trim() method like this:-

String z = x.substring(x.indexOf("ID:")+3, x.indexOf("Patient"));
z = z.trim();

Upvotes: 2

Related Questions