0

how could I convert my String to int array? my input:

String numbers = "123456";

What I'd like to reach:

Int numbers[]={1,2,3,4,5,6};

That String was splitted from String with this number.

Anush B M
  • 91
  • 1
  • 6
  • Assuming this to be in Java? – Anush B M Feb 14 '23 at 06:41
  • 3
    Please add a tag indicating what language you're using. @AnushBM guessed Java, but there are several languages that look similar. Don't make us guess. – Keith Thompson Feb 14 '23 at 06:53
  • Does this answer your question? [How to convert a String into an Integer\[\] array in Java?](https://stackoverflow.com/questions/53694806/how-to-convert-a-string-into-an-integer-array-in-java) – ytan11 Feb 17 '23 at 05:56

4 Answers4

1

If the above question is for Java.

 String numbers = "123456";
    int[] array = new int[numbers.length()];

        for (int i = 0; i < numbers.length(); i++) {
            array[i] = Character.getNumericValue(numbers.charAt(i));
            System.out.println("\n"+array[i]);
        }
Anush B M
  • 91
  • 1
  • 6
1

Java 8 one liner would be:

int[] integers = Stream.of( numbers.split("") )
  .mapToInt(Integer::valueOf)
  .toArray();
David Jones
  • 2,879
  • 2
  • 18
  • 23
0

I don't know what language you are working with. But I can tell you in c++.

character codes of digits start from 48(dec). You can add and remove this value for each element.

The code could roughly look like this.

int * _numbers=new int[numbers.size()];
for(int i=0;i<numbers.size();i++)
    _numbers[i]=numbers[i]+48;
0

The most straightforward way is to create an array variable and loop through the string characters and push them into the array.

var str = "123456";
var arr = [];

for (let n of str) {
  arr.push(parseInt(n))
}

console.log(arr);