Separate string array elements with next line \n or separator - java

I need some help with these strings. My code is:
String string = database.getCurrentDate();;
String[] array = string.split("[.]", 0);
String date = array[0] + "." + array[1];
String string1=database.getCurrentHour();
String[] array1=string1.split("[:]",0);
String hour=array1[0]+":"+array1[1];
String finalString=date+hour;// finalString is 28.0310:45
I need that finalString to be:
date
hour//on next line
example:
28.03//date
10:45//hour
The point is that I need the hour to be displayed on the next line, under date.
Thank you!

String finalString = date + "\n" + hour
Don't work if you display this?

Related

Splitting a string at a defined sign - especially "("

I have a little problem with splitting a String
String anl_gewerk = "Text Text Text (KG 412/2)"
String[] parts = anl_gewerk.split("[(]");
anl_gewerk = parts[1];
anl_gewerk = anl_gewerk.replaceAll("\\(","").replaceAll("\\)","");
anl_gewerk = anl_gewerk.replace("KG","");
I have the aforementioned string, and I'm searching for "412/2".
Therefore, I want to split the String into two substrings searching for "(".
Finally I want to grab this String deleting "(", "KG", " " and ")".
When I select anl_gewerk = parts[0]; it works but I get the wrong part, when I change into parts[1] the App crashes.
Please help me
Try to change your code by this:
String anl_gewerk = "Text Text Text (KG 412/2)";
String[] parts = anl_gewerk.split("[(]");
anl_gewerk = parts[1];
String sub[] = anl_gewerk.split(" ");
String test = sub[1];
String result = test.replace(")","");// it gives your result 412/2

Java, Substring to get value from string

given a string like this
string a = "Course Name:\n" + CourseName
+"\n\nVenue:\n" + locationName
+"\n\nStart Time:\n" + startTime
+"\n\nEnd Time:\n"+ endTime";
CourseName,locationName,startTime and endTime would be a variable and being assigned to string a, how can i get all these value from the string using substring or regex and store all of it into different variable? please note that I don't have access all these variable, I can only access the string which leave me the only option is play around with substring or regex.
You could split by newline
String[] parts = a.split("\\n");
String courseName = parts[1];
String locationName = parts[4];
String startTime= parts[7];
String endTime= parts[10];
or you can use:
StringTokenizer tokens=new StringTokenizer(a, "\n");
while(tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}

How to split a text that contains String and Int and store into an ArrayList?

So basically I have a java program that reads a txt file using BufferedReader.
The text file contains all the information about the movies. The first column is the code, the second is the title and the third is the rating.
e.g
1 Titanic 44
34 Avengers 60
2 The Lord of the Rings 100
So 1 is the code, Titanic is the title and 44 is the rating etc.
My problem is that I have made a class Movie(int code, String title, int rating)
and I want to store all the informations in there but I can't figure out how to split the text. split(" ") doesn't seem like it would handle the case where a title has embedded spaces (e.g The Lord of the Rings).
What I really need is the ability to strip off the first and last fields based on space as a separator, and treat all other interior spaces as part of the title, not as separators.
You are correct, split that you already tried is inappropriate. Based on the pattern you are showing, the delimiters seem to be the first and the last space in each line and everything between them is the title. I recommend to find the index of these spaces and use substring().
Eg:
String text = "2 The Lord of the Rings 100";
int firstSpace = text.indexOf(' ');
int lastSpace = text.lastIndexOf(' ');
String codeText = text.substring(0, firstSpace);
String title = text.substring(firstSpace, lastSpace);
String ratingText = text.substring(lastSpace);
You can use split(" ")
Use
String[] foo = split(" ")
The first element in foo will be the first integer. Convert that to an integer type. Then step through the remaining elements and append them into one string, except for the last element in foo, which will be your last integer and you can convert that to an integer type.
You can try this as you mentioned I can't use split(" ") because some titles (e.g The Lord of the Rings) has spaces between the title.
String str = "2 The Lord of the Rings 100";
String[] arr = str.split("\\s+");
List<String> list = Arrays.asList(arr);
Get the data for arr
String code = arr[0];
String rate = arr[arr.length-1];
String title = "";
for (int i = 1; i < arr.length-1; i++) {
title += arr[i]+" ";
}
Run the code
System.out.println("code = " + code);
System.out.println("rate = " + rate);
System.out.println("title = " + title);
And it is the result:
code = 2
rate = 100
title = The Lord of the Rings
May this help you...
See Regexp and Matcher classes with pattern : (\d*)\s(.*)\s(\d*)
EDIT : Example
#Test
public void testRegExp(){
String text = "2 The Lord of the Rings 100";
String patternString = "(\\d*)\\s(.*)\\s(\\d*)";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("CODE : " + matcher.group(1));
System.out.println("TITLE : " + matcher.group(2));
System.out.println("RATE : " + matcher.group(3));
}
}
String line = "1 Titanic 44";
int code = Integer.valueOf(line.split(" ")[0]);
String title = line.split(" ")[1];
int rank = Integer.valueOf(line.split(" ")[2]);

Assign a variable to a string of text that is between a certain delimiters Ex. “|” using Java

I have a string that I want to break down and assign different part of this string to different variables.
String:
String str ="NAME=Mike|Phone=555.555.555| address 298 Stack overflow drive";
To Extract the Name:
int startName = str.indexOf("=");
int endName = str.indexOf("|");
String name = str.substring(startName +1 , endName ).trim();
But I can't extract the phone number:
int startPhone = arg.indexOf("|Phone");
int endPhone = arg.indexOf("|");
String sip = arg.substring(startPhone + 7, endPhone).trim();
Now how can I extract the phone number that is between delimiter "|".
Also, is there a different way to extract the name using the between delimiter "=" & the first "|"
You can split on both = and | at the same time, and then pick the non-label parts
String delimiters = "[=\\|]";
String[] splitted = str.split(delimiters);
String name = splitted[1];
String phone = splitted[3];
Note that his code assumes that the input is formatted exactly as you posted. You may want to check for whitespace and other irregularities.
String[] details = str.split("|");
String namePart = details[0];
String phonePart = details[1];
String addressPart = details[2];
String name = namePart.substring(namePart.indexOf("=") + 1).trim();
String phone = phonePart.substring(phonePart.indexOf("=") + 1).trim();
String address = addressPart.trim();
I hope this could help.

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