Reputation: 1977
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]);
Upvotes: 2
Views: 1447
Reputation: 11989
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);
Upvotes: 1
Reputation: 16498
If you just want to print it out you may also try
System.out.println(Arrays.toString(dob.split("\\.")));
System.out.println(dob.replace(".", ":"));
Upvotes: 1
Reputation: 1502006
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.
Upvotes: 2
Reputation: 172518
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.
Upvotes: 4