SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Convert String to int Array

    Hi,guys!
    Is there any way to convert String s = "1234" to int[] s = {1,2,3,4}

    Thank you.

  2. #2
    Follow Me On Twitter: @djg gold trophysilver trophybronze trophy Dan Grossman's Avatar
    Join Date
    Aug 2000
    Location
    Philadephia, PA
    Posts
    20,580
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Code Java:
    String s = "1234";
    int[] intArray = new int[s.length()];
     
    for (int i = 0; i < s.length(); i++) {
    	intArray[i] = Character.digit(s.charAt(i), 10);
    }

  3. #3
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank a lot!

  4. #4
    SitePoint Member
    Join Date
    May 2009
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    simple and best answer... ,if performance is matters, better use For-Each loop instead of for loop...

  5. #5
    SitePoint Addict
    Join Date
    Aug 2007
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    how to impllement in for-each loop way?

  6. #6
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The for each won't work since you still need an index. You could use it but since you need the index anyway you might as well just use the for. Although it would look something like this.
    Code Java:
    String s = "1234";
    int[] intArray = new int[s.length()];
    char [] asChar = s.toCharArray();
    int i=0;
    for (char c : asChar) {
     intArray[i++] = Character.digit(c,10);
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •