1

How can I do this in Java or Android like:

String name = "Jhon Doe";
textView.setText("Hi " + name);
// I want only "Jhon" not "Doe"

I want only first name ("Jhon") not last name ("Doe")

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vishal Beep
  • 1,873
  • 1
  • 10
  • 25
  • 1
    You may want to read [https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – Mark Rotteveel Aug 14 '21 at 10:09

5 Answers5

1

Just use the java .split() function. It gives an array, with parts of the name, split by a space.

String name = "Jhon Doe";
String[] parts = string.split(" ");
textView.setText("Hi " + parts[0]);
lennart
  • 88
  • 6
0

Use can try below code

String name = "Jhon Doe";
String[] separated = currentString.split("\\s+");
String name =  separated[0]; // this will contain "Jhon"
0

You can use Java.String.split()

String string = "Jhon Doe";
String[] parts = string.split(" ");
String name = parts[0]; // Jhon
String surname = parts[1]; // Doe
textView.setText("Hi " + name);
vs97
  • 5,765
  • 3
  • 28
  • 41
0

Easiest way to do it.

String name = "Jhon Doe";
textView.setText("Hi " + name.split(" ")[0]);
Akash
  • 103
  • 8
0

If you prefer regex why not

String firstName = "John Doe".replaceFirst("^(\\w+).*$","$1")

Have fun.

Han
  • 728
  • 5
  • 17