Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting integer at each positions from a string S [duplicate]

Tags:

java

string

I accepted a number as string in java as S=1234 .NOW i want to get the integer values at s[0] s[1] s[2] s[3] .

for(int i=0;i<l;i++)// l is length of string s
    int x=s[i]-'0';// print this now

but this doesn't seem to work.

like image 542
satyajeet jha Avatar asked Apr 21 '26 09:04

satyajeet jha


1 Answers

Java strings aren't just char arrays, they're objects, so you cannot use the [] operator. You do have the right idea, though, you're just accessing the characters the wrong way. Instead, you could use the charAt method:

for(int i = 0; i < l; i++) { // l is length of string s
    int x = s.charAt(i) - '0';
    // Do something interesting with x
}
like image 149
Mureinik Avatar answered Apr 22 '26 23:04

Mureinik