-2

there. I faced a bit trouble with java programming

**Could someone give me a hint which of the method use in order to

string= "23578893762467290465" convert to array y= [2,3,5,7]....??** 

I mean, that for example y[0]=2, y[1]=3, y[2]=5....

Thanks in advance

2
  • 2
    string.toCharArray();
    – assylias
    Feb 14, 2013 at 10:18
  • Seems you want to convert to integer array...yes? Feb 14, 2013 at 10:21

4 Answers 4

2
String.toCharArray()

From the official documentation:

It returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

2

Convert String to an integer array.

String string= "23578893762467290465";
int[] intArray = new int[string.length()];
for(int i = 0; i<string.length(); i++){
    intArray[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
}
0
0
public class StringToInt{
public int[] convert(String arg){
    char[] characters = arg.toCharArray();
    int[] integers = new int[arg.length()];

    for ( int i = 0; i < characters.length; i++ ) 
        integers[i] = Character.getNumericValue(characters[i]);  

    return integers;
}

private void prettyPrint(int[] result){
    System.out.print("array: ");
    for(int i : result){
        System.out.print(i+" ");
    }
}

public static void main(String[]args){
    StringToInt converter = new StringToInt();
    int[] result = converter.convert(args.length > 0?args[0]: "23578893762467290465" );
    converter.prettyPrint(result);
}
}

ok, people beat me to it. But this'll work.

in essence:

  • Convert to char-array.
  • call Character.getNumericValue() for each character.
0

Another way may be:

int[] arr = new int[string.length()];

for(int i = 0; i<string.length(); i++){
    arr[i] = Character.getNumericValue(string.charAt(i));
    System.out.println(arr[i] + "  ") ;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.