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.
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.
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;
}
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
}
Got this information from another stack overflow response: Java: parse int value from a char
int x = Character.getNumericValue(S.charAt(i));
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));
}