-1

I have a string in the following format"

String s = name1, name2, name3, name4, name5,name6;

What is the best way out to get name1 out of this sing a generic solution which can be applied to a similar comma separated string?

Any help is appreciated.

user264953
  • 1,837
  • 8
  • 37
  • 63
  • possible duplicate of [What is the best way to extract the first word from a string in Java?](http://stackoverflow.com/questions/5067942/what-is-the-best-way-to-extract-the-first-word-from-a-string-in-java) – Alexis Leclerc Mar 25 '14 at 19:52

5 Answers5

30

You can use the split() method. It returns an array String[], so you can access to an element by using the syntax someArray[index]. Since you want to get the first elemnt, you can use [0].

String first_word = s.split(",")[0];

Note:

  • Indices in most programming languages start with 0. So the first elemnt will be in the index 0. The second in the index 1. So on.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
8

If you look at String.split(String regrex), you will find that it will return an array of strings.

name1 = s.split(", ")[0];

The [0] is the first index in an array, so it will be your name1. s.split(", ").length is equal to the size of the array, so if you ever need any index s.split(", ")[num-1] where num is the number of the index you want starting at one.

nimsson
  • 930
  • 1
  • 14
  • 27
2
String first = s.split(",")[0];

That should work perfectly fine for you.

SirTyler
  • 46
  • 1
2
 String parts[]=s.split(",");
             String part1=parts[0];

Use like this if you want to get the first name

Tech Nerd
  • 822
  • 1
  • 13
  • 39
1
s.split(",")[0];

Split gives you an array of Strings that are split up by the regex provided in the argument. You would want to check the length of the output of the split before using it.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68