How to convert a string to an int array in Java __java learning

Source: Internet
Author: User
Tags array length
How to convert a string to an array of int: three ways to provide
Import Java.util.Arrays;
public class strtointarr{
public static void Main (string[] args) {
String str = "1234567";
int[] demo01 = demo01 (str);
int[] demo02 = demo02 (str);
int[] demo03 = demo03 (str);
System.out.println (arrays.tostring (demo01));
System.out.println (arrays.tostring (demo02));
System.out.println (arrays.tostring (demo03));
DEMO04 (str);
}
Substring method using the parseint and string classes of the integer class (direct conversion method)
private static int[] demo01 (String str) {
int[] arr = new int[str.length ()];
for (int i=0; i<str.length (); i++) {
Arr[i] = Integer.parseint (str.substring (i,i+1));
}
return arr;
}
Using the Charat method of the string class and the Getnumricvalue method of the character class (indirect conversion method)
private static int[] demo02 (String str) {
int[] arr = new int[str.length ()];
for (int i=0; i<str.length (); i++) {
Arr[i] = Character.getnumericvalue (Str.charat (i));
}
return arr;
}
Another kind of indirect conversion method, ToCharArray method of String class
private static int[] demo03 (String str) {
char[] arr = new char[str.length ()];
int[] arr2 = new int[str.length ()];
arr = Str.tochararray ();
for (int i=0; i<str.length (); i++) {
Arr2[i] = arr[i]-48;//number 0~9 ASCII code is 48~57
}
return arr2;
}
Test the array length transformation in the process of string-turn character array to int array
private static void demo04 (String str) {
char[] arr = new char[str.length ()];
int[] arr2 = new int[str.length ()];
arr = Str.tochararray ();
for (int i=0; i<str.length (); i++) {
Arr2[i] = Arr[i];
}
System.out.println ("String length:" + str.length ());
System.out.println ("character array length:" + arr.length);
SYSTEM.OUT.PRINTLN ("int array length:" + arr.length);
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.