3

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.

satyajeet jha
  • 163
  • 3
  • 12

4 Answers4

1

You can get the integer by using charAt() in combination of getting the numeric value of that Character.

// Assuming you already have the Integer object "S" declared and assigned
int[] s = new int[Integer.toString(S).length()]; // create the integer array

for(int i = 0; i < Integer.toString(S).length(); i++)
{
  int x = Character.getNumericValue(S.charAt(i));
  s[i] = x;
}
A.Sharma
  • 2,771
  • 1
  • 11
  • 24
1

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
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Got this information from another stack overflow response: Java: parse int value from a char

int x = Character.getNumericValue(S.charAt(i));
Community
  • 1
  • 1
aus
  • 69
  • 1
  • 11
  • Once you have enough reputation, you can flag questions as duplicates. Plus, the other answer already provided that solution. – OneCricketeer Apr 28 '16 at 18:56
  • Oh cool, hopefully I'll be at that point soon. I must have been working on the answer at the same time. – aus Apr 28 '16 at 19:16
0

You can convert an numerical string just by using Character.getNumericalValue() method. below is the way to get it.

   String num = "1234";
    char[] a=num.toCharArray();
    ArrayList<Integer> p = new ArrayList<>();
    for(int i=0; i<a.length; i++){
        p.add(Character.getNumericValue(a[i]));
        System.out.println(p.get(i));
    }
Raj K
  • 458
  • 2
  • 7
  • 22