Reputation: 9225
I have the following dates:
"Friday, January 31",
"Wednesday, February 12",
"Monday, February 17",
"Wednesday, March 5",
I want to set up a string function where I am given the number always:
31
12
17
5
I started with this function:
String strCheck = suspendedDates[i];
int pos = strCheck.length();
int pos2 = strCheck.indexOf(" ");
I am stuck right now, because how does it know which " "
is it?
Can someone help me with the function.
Upvotes: 0
Views: 138
Reputation: 8246
Get the substring from the end. Instead of trying to figure out locations
strCheck.substring(strCheck.length()-2);
This will take the last two characters. Then just do a trim()
in case it's a single character to remove the space:-
strCheck.substring(strCheck.length()-2).trim();
Alternative
The other option as mentioned is to do a lastIndexOf()
on the String
with a space (" ") as an argument which will search backward from the end of the String
till it finds the space. But as the number can always be extracted in 2 character spaces, I see no reason to do 2 character compares every time you want to extract a known size String
(2) in a known location (length()-2
) in order to retrieve the location that you already know.
Upvotes: 2
Reputation: 240860
use lastIndexOf()
instead of indexOf()
final String str = "Friday, January 31";
System.out.println(str.substring(str.lastIndexOf(" ")));
Upvotes: 4
Reputation: 8617
I had to post it; since this is a date I would go with Date parse to allow an additional check on the format of the inputs:
An alternative way:
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM DD");
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse("Friday, January 31"));
System.out.println(new SimpleDateFormat("DD").format(cal.getTime()));
2nd SimpleDateFormat("DD")
is used instead of deprecated getDate()
.
Upvotes: 2
Reputation: 520
You can use something like this:
String str = "Friday, January 31";
Scanner s = new Scanner(s);
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
s.nextInt(); // get int
}
Upvotes: 1
Reputation: 14413
As an alternative of @JigarJoshi answer you can use a regex if you don't mind, removing all non-number characters.
String result = dateString.replaceAll("[^\\d]+","");
Upvotes: 2
Reputation: 1123
If you are trying to divide the string into parts for parsing, i suggest using String.split(" "), look at the javadocs and the internet for lots of nice examples of this in use! :)
Upvotes: 1