• 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
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.

Link to comment
Share on other sites

  • 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.

Link to comment
Share on other sites

  • 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
Link to comment
Share on other sites

  • 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.

Link to comment
Share on other sites

  • 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
Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

  • 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
Link to comment
Share on other sites

  • 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
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.