Ger Crowley
Ger Crowley

Reputation: 891

How can I get multiple characters from a string?

I'm trying to get the 5th, 6th and 7th digits from a list of digits.

E.g. I want to get the year out of the variable dateofbirth, and save it as a separate variable called dob, as an int.

Here is what I have:

int dateofbirth = 17031989
String s = Integer.toString(dateofbirth);
int dob = s.charAt(5);

What would I have to put in the parentheses after s.charAt to get a few digits in a row?

Upvotes: 2

Views: 19319

Answers (9)

smp7d
smp7d

Reputation: 5032

You want to use String.substring (untested):

int dateofbirth = 17031989;
String s = Integer.toString(dateofbirth);
String year = s.substring(4, 8);
int yearInt = Integer.parseInt(year);

Upvotes: 2

Petteri H
Petteri H

Reputation: 12212

If you are handling dates, you could use SimpleDateFormat and Calendar to pull out the year:

SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy"); 
Calendar cal = Calendar.getInstance();
cal.setTime(formatter.parse(Integer.toString(dateofbirth)));
int year = cal.get(Calendar.YEAR);

Upvotes: 1

jornb87
jornb87

Reputation: 1461

Integer.parseInt(s.subString(4))

Upvotes: 0

SJuan76
SJuan76

Reputation: 24885

From the JRE documentation: getChars

Upvotes: -1

Daniel Brockman
Daniel Brockman

Reputation: 19270

s.substring(5) will give you everything starting from index 5. You could also give a second argument to indicate where you want the substring to end.

Upvotes: 2

leifg
leifg

Reputation: 8988

This approach won't work for several reasons:

  1. s.charAt(5) will give you the ASCII code of the 6th character (which is not 9).
  2. There is no method to get several chars

If you want to extract 1989 from this string you should use substring and then convert this string into an Integer using Integer.valueOf()

Upvotes: 0

francesco.s
francesco.s

Reputation: 306

you do:

String s = String.valueOf(dateofbirth);
int yourInt = Integer.parseInt(s.substring(startIndex,length))

Upvotes: 0

Michael Berry
Michael Berry

Reputation: 72284

No need for the string conversion:

int dateofbirth = 17031989;
System.out.println(dateofbirth%10000); //1989

If you did want to do it as a string, then the substring() method would be your friend. You'd also need to use Integer.parseInt() to convert the string back into an integer. Taking a character value as an integer will give you the ASCII value of that character, not an integer representing that character!

Upvotes: 6

Related Questions