• 0

[JAVA] converting string to array


Question

I am in the process of writing simple a java program where I have to add arrays. This is what I am tying to do:

>Have my users input numbers ex: 12345

>put that input into an array with the data looking like: arr1[] = [1,2,3,4,5)

>

This is what I have. I am having the problem converting the string into an int array

import java.util.ArrayList;
import java.util.*;

public class Adding
{
  public static void main(String[] args)
  {
	Scanner in = new Scanner(System.in);

	String s = in.next();

	System.out.println(s);

	int [] n1 = new int [s.length()];



	for(int i = s.length() - 1; i >= 0; i++)
	{
	  char c = s.charAt(i);
	  int d = (int) c - (int) '0';
	  //this is where I am stuck - adding the data into the array
	}


  }
}

Link to comment
https://www.neowin.net/forum/topic/603102-java-converting-string-to-array/
Share on other sites

13 answers to this question

Recommended Posts

  • 0

Does it have to be an int array? You could easily just use the String.split() method with an argument of "" so that it splits at every character and then you'll have a string array. Then you can do the integer parsing when you actually need to use the items as integers.

  • 0

With s as your string:

String[] sArray = s.split("");

I've never used this in Java, but any other language that has a split type of method that I've seen allows for splitting between every character by using the empty string "".

This will automatically create your array of strings for you, as sArray, and then whenever you need to perform an operation as if the items were integers, you can use the Integer.parseInt() method to convert them to integers temporarily.

  • 0

From Sun:

http://java.sun.com/j2se/1.5.0/docs/api/ja...l#toCharArray()

toCharArray

public char[] toCharArray()Converts this string to a new character array.

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.

Then you can cast the char to an Integer at display time, obviously after checking that it is indeed an Integer... :D

Edited by Regression_88
  • 0
Then you can cast the char to an Integer at display time, obviously after checking that it is indeed an Integer...

OK, slow down. That's not what you think it is.

Don't confuse chars-as-integers and chars-as-part-of-a-String-representing-an-integer

in Java char is a two-byte integer type, so yo can always directly assign a char to a 4 byte int without casting or checking or possibility of errors. The value you get is the Unicode internal value of the char

If you want to know the integer represented by the ASCII/Unicode char, rather then the internal int value of the char, you need to parse the char, not cast it. The Integer class has a suitable constructor, which take a String, not a char as parameter, so no need to convert the Strings to chars at all.

  • 0

This should work:

import java.util.ArrayList;
import java.util.*;

public class Adding
{
	public static void main(String[] args)
	{
		Scanner in = new Scanner(System.in);

		String s = in.next();

		System.out.println(s);

		int [] n1 = new int [s.length()];



		for(int n = 0; n < s.length(); n++)
		{
			n1[n] = Integer.parseInt(s.split("")[n]);
		}


	}
}

Actually splitting on "" doesn't work in Java... look into the .getChars() method to turn the String into a char array then parse each one into an int.

Edited by Borbus
  • 0
Actually splitting on "" doesn't work in Java... look into the .getChars() method to turn the String into a char array then parse each one into an int.

...or simply take a 1-long substring

	for(int n = 0; n < s.length(); n++)
		{n1[n] = Integer.parseInt(s.substring(n,n+1));
	}

  • 0
I am in the process of writing simple a java program where I have to add arrays. This is what I am tying to do:

>Have my users input numbers ex: 12345

>put that input into an array with the data looking like: arr1[] = [1,2,3,4,5)

>

This is what I have. I am having the problem converting the string into an int array

You should really get into the habit of naming your variables with useful names, not "s", "c", "d" and "n1".

The code to add an element into an array is:

myArray[#] = <some value>;

where # is the index in the array you want to insert <some value>.

Remember that arrays are 0-indexed, which means the first element in an array is at index 0, the second element at index 1... the nth element at index (n-1).

In your case, you want to say:

n1[i] = d;

  • 0

You're all over complicating this. You get the characters of the String as an array, and parse them as ints.

And you need some more help understanding for loops, yours is a bit crazy :)

import java.util.*;

public class Adding
{
	public static void main (String[] args)
	{
		Scanner in = new Scanner (System.in);
		String s = in.next ();
		// Dont really need this line:
		System.out.println (s);
		char[] chars = s.toCharArray ();
		int[] n1 = new int[chars.length];

		for (int i = 0; i &lt; chars.length; ++i)
		{
			// This will throw a MalformedNumberException (from memory),
			// if you give it a non-numerical char, so it really needs a try-catch
			// to ignore it and carry on, but I dont think you know about those
			// yet?
			n1[i] = Integer.parseInt(String.valueOf(chars[i]));
		}

		// Print out our array to make sure it's ok
		for (int num : n1) System.out.print(num);
	}
}

Could do with some syntax highlighting ;)

  • 0

Why bother converting the String to a char array then converting the chars back to Strings? It's a load of un-needed complexity. Just go:

	String s = in.next ();
	int[] n1 = new int[s.length];
	for(int n = 0; n &lt; s.length(); n++)
		{n1[n] = Integer.parseInt(s.substring(n,n+1));
	}
	for (int num : n1) System.out.print(num);

  • 0

A string is already an array .. an array of chars I think? I'm pretty sure I've done string.charAt(i) on things before...

from the Java API

http://java.sun.com/j2se/1.5.0/docs/api/

String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};

String str = new String(data);

The code I would use would be something like this:

String[] numberString = whatever;
Int[] numberArray = new int[numberString.length()];

for (int i=0; i&lt; numberString.length(); i++){
	numberArray[i] = numberString.getChar(i);


}

Edited by Persephone
  • 0

Persephone, this mistake is all too easy to make.

char is an integer data type, not the same as a one-letter String. Assign a char to an int and you get the internal representation of whatever the char is.

This problem calls for the number represented by the character, ie '1' should give the integer 1, not 49.

Converting the String values to char at best creates unneeded complexity, at worst leads to String/int confusion and the wrong result.

Edited by JamesCherrill
This topic is now closed to further replies.
  • Posts

    • Yeah, when I saw that, I wanted to find the nearest nose. You can't find a good nose these days when you need one.
    • Anthropic launches Claude Fable 5, a state-of-the-art AI model that beats OpenAI's GPT-5.5 by Pradeep Viswanathan Back in April, Anthropic announced Claude Mythos Preview, a frontier model with state-of-the-art coding capabilities. Due to the cybersecurity implications that would occur due to the availability of such a powerful model, Anthropic made it available to only a select set of companies around the world. The company's plan was to prepare appropriate guardrails before releasing such a powerful model to everyone. Now, after nearly two months, Anthropic announced Claude Fable 5, its most capable AI model yet for general users. The company also announced Claude Mythos 5, the same underlying model as Fable 5, but with safeguards lifted, making it more suitable for selected cybersecurity and biology use cases. Claude Fable 5 sits a tier above its Opus models and it beats most other generally available models across areas including software engineering, knowledge work, vision, scientific research, and long-running autonomous tasks. To prevent model misuse, when Claude Fable 5 detects certain requests related to cybersecurity, biology, chemistry, or model distillation, the request will be routed to the Claude Opus 4.8 model. Anthropic claims that these safeguards trigger in less than 5% of sessions on average. However, for large organizations working on critical software, Claude Mythos 5 can be availed through Project Glasswing. Later, Anthropic has plans to expand access through a broader trusted access program. As you can notice in the benchmarks above, Fable 5 and Mythos 5 are state-of-the-art on most key AI benchmarks and they are well ahead of OpenAI's frontier model, GPT-5.5. For example, Fable 5 is the new state-of-the-art model for vision tasks. Also, Mythos 5 has the strongest cybersecurity capabilities of any model in the world. Claude Fable 5 and Claude Mythos 5 are priced at $10 per million input tokens and $50 per million output tokens, which is less than half the price of Claude Mythos Preview. Another big change is that Anthropic is making a change to the way they handle business customer data for both Fable 5 and Mythos 5 models. The company will now require 30-day retention for all traffic on both first- and third-party surfaces. Anthropic promises that it won't use the data to train Claude models, instead it will use it against complex and novel attacks. Claude Fable 5 is available today on the Claude API and consumption-based Enterprise plans. It is also included at no extra cost for Pro, Max, Team, and seat-based Enterprise customers from today through June 22. After that, users on those plans will need usage credits to continue using Fable 5, unless Anthropic extends the included access window based on capacity. Developers can access Fable 5 through the Claude API using the claude-fable-5 model name.
    • Dragon's Dogma 2: Dark Arisen expansion to bring snowy region, new updates also coming by Pulasthi Ariyasinghe Capcom had a surprise waiting for Dragon's Dogma fans today in the Nintendo Direct presentation. The company revealed an expansion for the second installment with a name that should be familiar to series veterans. Coming later this year, Dragon's Dogma 2: Dark Arisen is promising a massive new region to explore, new monsters, fresh skills to learn, and more. The studio says players will be heading to the Northern region of the world, named Norgan, to find new secrets about an undying "Fallen Dragon." There will be forgotten relics that the protagonist can find to unlock fresh weapons and skills the expansion is introducing. Players will also be able to find mysterious equipment from a previous Arisen as a part of the expansion, all part of 12 Lost Rites Dungeon Challenges they must complete to gain access. In Neowin's own review, I found Dragon's Dogma 2 to be an impressive RPG when it launched back in 2024, giving the title an 8.5/10 for its class variants, companion system, and immersive exploration. "Once a prosperous region of the kingdom of Vermund, it was abandoned many years ago for reasons unknown," says Capcom about the new region. "Long has it been since any soul traveled its paths. Blanketed in heavy snow, these frigid lands are home to savage hordes and creatures of unbelievable power. Those who are capable of vanquishing such fearsome foes, or those who possess a keen eye for exploration, will find themselves rewarded with powerful relics." Dragon’s Dogma 2: Dark Arisen expansion launches on October 9, 2026, with a $29.99 price tag. Ahead of the expansion release, Capcom is also planning to release two free updates to the base game. The first will land tomorrow, June 10, bringing more accessible fast travel with an Eternal Ferrystone and other quality-of-life adjustments. The second update will land sometime in August, aiming to improve frame rates, add more save slots, and bring even more community-requested adjustments. This expanded Dark Arisen edition is also launching on the Nintendo Switch 2 on the same day the content comes to PC, Xbox Series X|S, and PlayStation 5.
  • Recent Achievements

    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
    • One Year In
      jojodbn earned a badge
      One Year In
    • One Month Later
      jojodbn earned a badge
      One Month Later
    • Week One Done
      jojodbn earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      525
    2. 2
      PsYcHoKiLLa
      231
    3. 3
      +Edouard
      124
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!