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.

3
  • Assuming this to be in Java? Commented Feb 14, 2023 at 6: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. Commented Feb 14, 2023 at 6:53
  • Does this answer your question? How to convert a String into an Integer[] array in Java? Commented Feb 17, 2023 at 5:56

5 Answers 5

2

Java 8 one liner would be:

int[] integers = Stream.of( numbers.split("") )
  .mapToInt(Integer::valueOf)
  .toArray();
Sign up to request clarification or add additional context in comments.

Comments

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]);
        }

Comments

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);

Comments

0

The above answers are more straightforward ways to do achieve this; however, you can also take the substring of the array between a value of i and i+1, parse that string as an integer, and then assign the array at index i to the value of the integer to achieve the same goal. Here is the code below:

    public class StringtoIntArray {
        public static void main(String[] args) throws Exception 
        {
            String numbers = "123456";
            int[] array = new int[numbers.length()];

            String temp; 
            int holder;

            for(int i=0;i<numbers.length();i++)
            {
                temp=numbers.substring(i,i+1);
                holder = Integer.parseInt(temp);
                array[i]=holder;
                System.out.println(array[i]);
            }
        }
    }

Comments

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;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.