• 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.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Still 3x what it should cost. So, it seems the trick is to increase price by 6x so that a reduction in price back to 4x looks like a steal. "You savvy shoppers win again!" I'm glad I'm not in a desperate spot to actually even need this overpriced crap. Hopefully, it comes back down by the time for when (or if) I ever do.
    • Although AI is great and has it's use cases they likely have massively overhyped it and it has not delivered as per their expectations. I fully expect them to start saying the same things again when it does get to a certain level of intelligence!
    • Microsoft wants to end printer driver headaches with Windows Ready Print by Usama Jawad A few days ago, Microsoft released Windows 11 Experimental build 26300.8553, bringing a ton of enhancements such as Start menu customization, search improvements, Taskbar polish, and other minor UI tweaks. Another relatively major enhancement snuck deep within the change log was related to upgrades to the Windows printing experience. Now, Microsoft has shared more details about these benefits. For starters, Microsoft has renamed its Modern Print Platform to Windows Ready Print. The company believes that this name highlights its shift in strategy, which now focuses on modernizing, securing, and streamlining the printing experience for Windows devices. Some of the upgrades present in Windows Ready Print have already been seeded to customers and partners. This includes ending support for third-party printer drivers via Windows Update and transitioning towards the Internet Printing Protocol (IPP) and the native Windows IPP printer driver. In line with these changes, new printer installations will default to Windows Ready Print on eligible devices starting from July 2026. However, Microsoft recognizes that not all environments will be able to migrate to this platform immediately, so it will allow users to choose between installing the printer via Windows Ready Print or the traditional OEM process. Users will be able to toggle this configuration through Settings > Bluetooth & Devices > Printers & Scanners > Printer preferences. This control applies only to new printer installations, and its functionality can also be modified via Group Policy as follows: Launch Group Policy Editor Navigate to Local Computer Policy -> Administrative Templates -> Printers Find and select 'Configure Windows Ready Print driver ranking' -> double click to open it Select 'Enabled' (if you wish to enable Windows Ready Print driver selection) or 'Disabled' (if you wish to explicitly disable Windows Ready Print driver selection). Select Apply Select OK Similarly, if you set up Windows protected print mode through the same setting in Windows 11, it will also default to using Windows Ready Print exclusively. Microsoft hopes that these improvements will help eradicate dependency on OEM-specific driver installation processes and simplify printer installations. We'll likely find out more about other tangible benefits in the coming months.
    • Hey what's about the proton vpn firefox extension ? It's not working today
  • Recent Achievements

    • One Year In
      Primer1st earned a badge
      One Year In
    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      513
    2. 2
      PsYcHoKiLLa
      229
    3. 3
      Edouard
      137
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      81
  • Tell a friend

    Love Neowin? Tell a friend!