How to split this string using split function() - java

I hava one string "2013-1-31 08:25 PM"
i want to split from space and :
i able to split after space it become "2013-1-31 08" and "25 PM"
now i want the "2013-1-31" and "08"
i dont not able to get the value in the 08 in the new string but i get the "2013-1-31"
String view_datee = view_date.getText().toString();
String[] separated = view_datee.split(":");
String first =separated[0];
String second=separated[1];
String[] newSeperated = first.split(" ");
String third = newSeperated[0];
String four= newSeperated[1];
Log.i("first",first);
Log.i("second",second);
Log.i("third", third);
Log.i("four", four);
I do not how to get the four value means 08 .

Here is an example using a date / calendar (it uses desktop java but easily transposable):
public static void main(String args[]) throws Exception {
String data = "2013-1-31 08:25 PM";
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Calendar cal = Calendar.getInstance();
cal.setTime(fmt.parse(data));
//2013-1-31
System.out.println(new SimpleDateFormat("yyyy-M-dd").format(cal.getTime()));
//20
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
//08
System.out.println(new SimpleDateFormat("hh").format(cal.getTime()));
}
Note that 08:25 PM is 20:05 so you can get either 08 or 20 depending on what you need. I showed both in my example.

Try this,
public static void main(String[] args) {
String str = "2013-1-31 08:25 PM";
System.out.println("[Date:"+str.split(" ")[0]+"][Hours:"+str.split(":")[0].split(" ")[1]+"]");
}
Output,
run:
[Date:2013-1-31][Hours:08]
BUILD SUCCESSFUL (total time: 1 second)

From the official Javadoc, split takes a RegExp as argument.
So, you cannot use " " as split argument.
Instead, you should use "\s" to sepparate the string by whitespace.
Then, your code would be:
String[] separated = view_datee.split(":");
String first =separated[0];
String second=separated[1];
String[] newSeperated = first.split("\\s");
String third = newSeperated[0];
String four= newSeperated[1];
Log.i("first",first);
Log.i("second",second);
Log.i("third", third);
Log.i("four", four);

Are u sure String ends with PM Or AM
Then u can do like this
String s= "2013-1-31 08:25 PM";
String newStr=s.substring(s.indexOf(" ")+1,s.lastIndexOf(" "));
System.out.println(newStr);
String result[]=newStr.split(":");
System.out.println(result[0]);
System.out.println(result[1]);

check below code, its working properly
String date = "2013-1-31 08:25 PM";
String[] split = date.split(":");
System.out.println(split[0]+"date:::" + split[1] );
String[] Datesplit = split[0].split(" ");
System.out.println(Datesplit[0]+"date splited:::" + Datesplit[1] );
Output below
2013-1-31 08date:::25 PM
2013-1-31date splited:::08

I have checked out your code and its working properly..
Here is i am posting whatever i have typed and excuted:
String teststr = "2013-1-31 08:25 PM";
System.out.println("teststr: " + teststr);
String[] separated = teststr.split(":");
String first = separated[0];
String second = separated[1];
String[] newSeperated = first.split(" ");
String third = newSeperated[0];
String four = newSeperated[1];
System.out.println("first : "+first);
System.out.println("second : "+second);
System.out.println("third : "+third);
System.out.println("fourth : "+four);
and its giving me following output:
teststr: 2013-1-31 08:25 PM
first : 2013-1-31 08
second : 25 PM
third : 2013-1-31
fourth : 08

Related

Extracting a substring from a given string pattern

Here are the Strings:
Example 1 - Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo
Example 2 - Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012
How can I extract values like old_actor, new actor from example 1 and new_movie_release_date and old_movie_release_date from example 2.
I'm new to regex trying to see how can this be done. Thanks in advance.
You can do using java regex as follows
String str1 = "Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo";
String str2 = "Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012";
String pattern1="Movie=(.*?);old_actor=(.*?);new_actor=(.*?)$";
String pattern2="Movie=(.*?);old_movie_release_date=(.*?);new_movie_release_date=(.*?)$";
Matcher m1 = Pattern.compile(pattern1).matcher(str1);
if (m1.find()) {
System.out.println("old_actor: " + m1.group(2));
System.out.println("new_actor: " + m1.group(3));
}
Matcher m2 = Pattern.compile(pattern2).matcher(str2);
if (m2.find()) {
System.out.println("old_movie_release_date: " + m2.group(2));
System.out.println("new_movie_release_date: " + m2.group(3));
}
You could use String.split(String regex).
First, you use String.split(";"), which will give you an array String[] values with contents looking like Movie=moviename, then you use String.split("=") on each string in the first array
for(String str : values) {
String[] keyValue = str.split("=");
}
to create subarrays of length 2 with key at position 0 and value at position 1.
Just an enhancement to #DerLebkuchenmann's solution
public static void main(String[] args) {
String str1 = "Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo";
String str2 = "Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012";
Map<String, String> props1 = getProps(str1);
Map<String, String> props2 = getProps(str2);
System.out.println(String.format("Old Actor: %s", props1.get("old_actor")));
System.out.println(String.format("Old Movie Release Date: %s", props2.get("old_movie_release_date")));
System.out.println(String.format("New Movie Release Date: %s", props2.get("new_movie_release_date")));
}
private static Map<String, String> getProps(String str1) {
return Arrays.stream(str1.split(";"))
.map(pair -> pair.split("="))
.collect(Collectors.toMap(crumbs -> crumbs[0], crumbs -> crumbs[1]));
}
Another approach using StringTokenizer and assembling a HashMap for result:
public class Main
{
public static void main(String[] args) {
HashMap<String,String> m = new HashMap<String,String>();
StringTokenizer st = new StringTokenizer("Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo",";=");
while(st.hasMoreTokens()) {
String s = st.nextToken();
if (st.hasMoreTokens()) { // ensure well-formed
m.put(s,st.nextToken());
}
}
System.out.println(m);
}
}
Prints:
{Movie=HULK/Incredible HULK, old_actor=Edward Norton, new_actor=Mark Ruffalo}

reading a whole date and time with spaces in a file

this question may have been asked before but didn't find any clue for my problem here,
here is my problem : I have a file that is like this :
abc fg Sat Jan 08 19:06:21 IST 2022 4 4.0
here is my code that reads from the file :
BufferedReader read4 = new BufferedReader(new FileReader("shortDelvsFile.txt"));
while ((s = read4.readLine()) != null) {
token = new StringTokenizer(s);
double str1 = Double.parseDouble(token.nextToken());
Integer str2 = Integer.parseInt(token.nextToken());
while (token.hasMoreTokens()) {
System.out.println(convert(token.nextToken()));
}
ShortDeliveries d = new ShortDeliveries(token.nextToken(), token.nextToken(),
convert(token.nextToken()), str2, str1);
shortDelvss.add(d);
}
System.out.println("the short deliveries are : " + shortDelvss);
read4.close();
// this function is to convert the string to date
public static Date convert(String s) throws ParseException {
Date date = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH).parse(s);
System.out.println(date);
return date;
}
now i want each ``token.nextToken();``` inside the ShortDeliveries to be like this:
token.nextToken() = fg
convert(token.nextToken()) = Sat Jan 08 19:06:21 IST 2022
str1 = 4
str2 = 4.0;```
the problem is that in convert(token.nextToken()) it doesn't take the whole date because tokenizer reads until the first space how can i fix that?
In case you know the date will always start with the day of week (e.g. Sat, Sun...), you can create a method to check if the current token is a known day.
In case this is a week day, collect the following 6 tokens (or whatever tokens count you need to form a valid date) and send them together as String to your convert method.
if (isDayOfWeek(token)) {
List<String> dateTokens = getNextTokens(token, 6);
String dateString = String.join(" ", dateTokens);
Date date = convert(dateString);
}
private boolean isDayOfWeek(String dayString) {
Locale locale = Locale.getDefault();
return Arrays.stream(DayOfWeek.values())
.map(day -> day.getDisplayName(TextStyle.SHORT, locale))
.anyMatch(dayString::equals);
}
private List<String> getNextTokens(StringTokenizer token, int tokenCount) {
return IntStream.rangeClosed(1, tokenCount)
.mapToObj(i ->token.nextToken())
.collect(Collectors.toList());
}
"s" is just a string that represents one line of your data
If you process it like a variable instead of a stream, you can use split.
There are several ways to do this, my preferences is as follows:
String parts_of_s = s.split(" ");
String s1 = s[0]; // you can in-line converting to double as you did above
String s2 = parts_of_s[1];
String remaining_string = s.substring(s1.length()+1 + s2.length()+1); // length indexes at zero
String string_date = remaining_string.substring(0, 28); // since you know how many characters there are in the format
String s3 = parts_of_s[8];
String s4 = parts_of_s[9];
If you're dealing with super-long lines of data where efficiency matters (you probably won't), you could pursue other avenues:
read the next 28 characters
read the next 6 tokens and concatenate with a space

Reading GEDCOM files: How to substring the corresponding birth day, month, and year, into an Integer variable from an input file to an output file

I have an input GEDCOM file with tons of individual/family records. The purpose is to format their data into this form:
name(p6, 'Harry Buis').
birth(p6, date(1927,11,17)).
death(p6, date(2001,08,21)).
famc(p6, f3).
fams(p6, f2).
I have been able to pull out the person number and their name and print it to an output file, however I am having trouble parsing the birth/death dates. I want to be able to use substring to assign the birthDay, birthMonth, and BirthYear as Integers so I can print it to the output file. It must be Integers so I can sort by date. Here is a sample of one client's data from the input file.
0 #P6# INDI
1 BIRT
2 DATE 17 Nov 1924
1 NAME Harry /Buis/
1 DEAT Age: 76
2 DATE 21 Aug 2001
1 SEX M
1 FAMC #F3#
1 FAMS #F2#
And here is my source code of what I have so far:
public class Main {
static Scanner scan;
static BufferedWriter outFile;
static int birthYear = 0;
static int birthMonth = 0;
static String birthDay = "";
static int deathYear = 0;
static int deathMonth = 0;
static int deathDay = 0;
static String name = "";
static String person = "";
static String sex = "";
static String famC = "";
static String famS = "";
static String man = "";
static String woman = "";
static String child = "";
public static void parse() throws IOException {
scan = new Scanner(new FileReader("pbuis.ged"));
outFile = new BufferedWriter(new FileWriter("output.txt"));
String reader = scan.nextLine();
int count = 0;
while (scan.hasNextLine()) {
if (reader.contains("NAME") && count < 1) {
reader = reader.substring(1).replace("/", "");
count++;
System.out.println(reader);
name = reader.replace("NAME", "");
}
if (reader.startsWith("0")) {
person = reader.trim().substring(2, 7).replace("#", "")
.replace("I", "").trim().toLowerCase();
System.out.print(person);
count = 0;
}
if (reader.contains("BIRT")) {
scan.nextLine();
birthDay = Integerreader.substring(6, 9).trim();
}
if (reader.equalsIgnoreCase("") || reader.equalsIgnoreCase(" ")) {
outFile.write("name(" + person + ", " + "'" + name.trim() + "'"
+ ")." + "\n" + birthDay);
}
reader = scan.nextLine();
}
}
public static void main(String[] args) throws IOException {
parse();
}
}
Without the if statement (contains "BIRT"), and "birthDay" not in the outFile.write() method, my output looks like this:
name(p1, 'Paul Edward Buis').
name(p2, 'Thomas Edward Buis').
name(p3, 'Jennifer Joy Buis').
name(p4, 'Daniel Paul Buis').
name(p5, 'Barbara Joy VanderWall').
name(p6, 'Harry Buis').
which is a good start.
But when I have that if statement, I get an error like this, and nothing prints:
p1Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
at java.lang.String.substring(Unknown Source)
at Main.parse(Main.java:50)
at Main.main(Main.java:64)
Now, I have tried every combination of substringing index values, and nothing seems to work. Any idea on how I fix this?
Thanks in advance.
I suggest you use a Date function. Date functions can be sorted easier than year/month/date. If you really want, store them as the milliseconds since the epoch.
To parse the date, use a SimpleDateFormatter. I believe something like this would work:
SimpleDateFormatter dateFormat=new SimpleDateFormat("dd mmm yyyy")
Date birth=date.parse("17 jul 1984",0);
One you get it in to the Date format, you can do a lot of neat things, like these:
Date date1, date2;
date1.after(date2);
date1.compareTo(date2)
You could even get the minutes or seconds, but I don't recommend that. Note the 0 refers to the index starting the string, so you could just specify the index where the format starts, and you're good. Overall, I think this is a lot cleaner.
Date parsing from GEDCOM files is tricky. You can use a SimpleDateFormatter for any dates that are in dd MMM yyyy format (like 26 SEP 2015) but GEDCOM supports a lot of weird variations, including imprecise dates where you only have the month and year, or just the year. It also allows prefixes like "ABT" to indicate that something occurred around a specific date, allows for ranges ("BET date1 AND date2") and ("FROM date1 TO date2"), and a lot of other complex behavior (French Republican or Hebrew calendars, anyone?)
I would recommend using gedcom4j (http://gedcom4j.org), which is a java library you can link into your program to load your data into Java objects and then do what you need. The DateParser class in that library can interpret your string values and turn them into java.util.Date values so you can do what you're describing.

Using space as delimiter

I am trying to delimit the , and space my input is 21, May, 2012 my output should be 2012-May-21.
String s = args[0];
String[] s1 = s.split(",\\s+");
System.out.print(s1[2] + "-" + s1[1] + "-" + s1[0]);
It is working if I am writing for only , delimiter but getting ArrayIndexOutOfBoundsException when trying for space as delimiter.
Since both ,,space are optional as mentioned in the comment..
String[] s1 = s.split(",|\\s+");
Though I won't use regex to parse date
input=input.replaceAll("\\s*","");//remove any space if any
java.util.Date date= (new SimpleDateFormat("dd,MMM,yyyy")).parse(input);
String output=(new SimpleDateFormat("yyyy-MMM-dd")).format(date);
Try this,
String date = " 21 , May, 2012";
String[] s1 = date.split(",\\s*");
System.out.println(s1[2].trim() + "-" + s1[1].trim() + "-" + s1[0].trim());
You can also do this using String#replaceAll :
s.replaceAll(",\\s*", "-");

How to delete all the characters after one character in the String?

I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"
I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.
Four options (last two added to make this one answer include the options given by others):
Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
Find the first space using indexOf and get the leading substring using substring:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
text = text.substring(0, spaceIndex);
}
Trust that it's valid in the specified format, and that the first space will always be at index 10:
text = text.substring(0, 10);
Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)
text = text.split(" ")[0];
You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.
Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?
String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];
Try this:
String date = s.substring(0, s.indexOf(" "));
Or even (because the length is fixed):
String date = s.substring(0, 10);
Or use StringUtils.substringBefore():
String date = StringUtils.substringBefore(s, " ");
Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];
You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]
In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat
.
You can use substring to extract the date only:
String thedatetime = "01-01-2012 01:01:01";
String thedateonly = thedate.substring(0, 10);
You should really read through the javadoc for String so you are aware of the available functions.
If you know in advance this is the format of the string, I'd do this:
public String getDateOnly(String fullDate){
String[] spl = fullDate.split(" ");
return spl[0];
}
You can do it either using string manipulation API:
String datetime = "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
String date = datetime.substring(0, spacePos - 1);
}
or using regular expression:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime = "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
String date = m.group(1);
}
or using SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();
Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.
myString.substring(0,10);
If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.
If you want to explode the complete date from the string use this method.
/**
* #param dateTime format string
* #param type type of return value : "date" or "time"
* #return String value
*/
private String getFullDate(String dateTime, String type) {
String[] array = dateTime.split(" ");
if (type == "time") {
System.out.println("getDate: TIME: " + array[1]);
return array[1];
} else if (type == "date") {
System.out.println("getDate: DATE: " + array[0]);
return array[0];
} else {
System.out.println("NULL.");
return null;
}
}
Otherwise if you want only the date for explample 01-01-2012
use this:
/**
* #param datetime format string
* #return
*/
private String getOnlyDate(String datetime) {
String array[] = datetime.split("-");
System.out.println("getDate: DATE: " + array[0]);
return array[0];
}
I hope my answer will help you.

Categories