2

I am trying to split String with dot i am not able to get answer

String dob = "05.08.2010";
String arr[] = dob.split(".");
System.out.println(arr[0]+":"+arr[1]+":"+arr[2]);
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
Ashish Agrawal
  • 1,977
  • 2
  • 18
  • 32

4 Answers4

4

Try this

String arr[] = dob.split("\\.");

ie, you need to put the double slash to escape the dot as dot will match any character in regex. Also note that double backslash is used to create a single backslash in regex.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

String.split takes a regular expression pattern. . matches any character in a regex. So you're basically saying "split this string, taking any character as a separator". You want:

String arr[] = dob.split("\\.");

... which is effectively a regex pattern of \., where the backslash is escaping the dot. The backslash needs to be doubled in the string literal to escape the backslash as far as the Java compiler is concerned.

Alternatively, you could use

String arr[] = dob.split(Pattern.quote("."));

... or much better use date parsing/formatting code (e.g. SimpleDateFormat or DateTimeFormatter) to parse and format dates. That's what it's there for, after all - and it would be better to find data issues (e.g. "99.99.9999") early rather than late.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

In the split function do not use . because it's a Regular Expression special character and need to be escaped: \\.

You can also parse date using

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateInString = "05.08.2010";
Date date = sdf.parse(dateInString);

EDIT

Now you can access day / month / year using (see this thread)

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
Community
  • 1
  • 1
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • i am asking how to split date so i can use dd MM yyyy separately – Ashish Agrawal Oct 09 '15 at 07:02
  • you can use the date object to get the day / month / year separately ([java date documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html)). You can do `date.getMonth()` for example. – ThomasThiebaud Oct 09 '15 at 07:04
  • 2
    You should absolutely *not* use `date.getMonth()` etc. There are very good reasons why those methods are deprecated, and have been for nearly 20 years. – Jon Skeet Oct 09 '15 at 07:38
  • I did not see it. But you still can get day / month / year from a date object (see edit) – ThomasThiebaud Oct 09 '15 at 07:40
1

If you just want to print it out you may also try

System.out.println(Arrays.toString(dob.split("\\.")));

System.out.println(dob.replace(".", ":"));
Eritrean
  • 15,851
  • 3
  • 22
  • 28