3

I have a method that returns a String. That string called contact is made of multiple smaller strings. Those smaller strings were parameters to that method.

exemple :

String contact = id + " " + name + " " + telNum;
return contact;

Now I have another method that takes contact as a parameter but that needs to return ONLY name.

So my question is how can I isolate that smaller string name from the whole string contact?

Maroun
  • 94,125
  • 30
  • 188
  • 241

5 Answers5

2

Use

String[] splits = contact.split(" ");
String name = splits[1];
Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
1

The answer of Viswanath shows how to retrieve the name from the string using string functions.

As an alternative you could consider to create a Contact class which holds the information:

 public class Contact {
     public String id;
     public String name;
     public String tel;

     public String toString() { return id + " " + name + " " + telNum; }
 }

and then pass a Contact object around instead of the string which represents the contact .

wero
  • 32,544
  • 3
  • 59
  • 84
0

If your ID has only numbers and telephone number is starting with + or any digit then you can easily get name out of it.

MDaniyal
  • 1,097
  • 3
  • 13
  • 29
0
String name = contact.substring(contact.indexOf(" ", 0)+1, contact.indexOf(" ", contact.indexOf(" ", 0)+1);
Jordy Baylac
  • 510
  • 6
  • 18
0

If id and telNum are two integer/long values you can do something like

int startIndex = contact.indexOf(" ");
int endIndex = contact.lastIndexOf(" ");
String name = contact.substring(startIndex, endIndex).trim();

It should be easier if your string has separators, like comma.

Ex.:  String contact = id + ", " + name + ", " + telNum;

In this case you could do the same of above but searching the index of "," or of ", ".

McGiogen
  • 654
  • 8
  • 17