简体   繁体   中英

how can i get int array from the string

i want to make the number array from the StringTokenizer.

if there is text line " 2345 "
i want to get array list [2,3,4,5] . so first of all, i made Arraylist and get from the st token using the hasMoreToken

ArrayList argument_list = new ArrayList();
 while(st.hasMoreTokens()){
    argument_list.add(Integer.valueOf(st.nextToken()));
}
int[] arguments = new int[argument_list.size()];

now i notice my argument_list get whole string to number "2345" not "2","3","4","5" because there is no "split word" like " , "

maybe i can divide number use the "/" but i think there is a way just split the String and get the number array even i don't know

is there way to split the token to array ?

Another approach is to use String#toCharArray , and work with resulting char[]

List<Integer> ints = new ArrayList<Integer>();
char[] chars = "2345".toCharArray();
for (char c : chars) {
    ints.add(Integer.parseInt(String.valueOf(c)));
}

You could also convert to char array in loop declaration, removing the need for chars variable

List<Integer> ints = new ArrayList<Integer>();
for (char c : "2345".toCharArray()) {
    ints.add(Integer.parseInt(String.valueOf(c)));
}

you can try something like this:

String s = "1234";
int[] intArray = new int[s.length()];

for (int i = 0; i < s.length(); i++) {
    intArray[i] = parseInt(s.charAt(i));
}

Try Following:

    String s="12345";
    String test[]=s.split("(?<!^)");

    int[] arguments = new int[test.length];
    for(int i=0;i<test.length;i++){
        arguments[i]=Integer.parseInt(test[i]);
    }

The code splits the string into each character and later parses it to integer.

Try something like:

String s = "1234";
int[] intArray = new int[s.length()];

for (int i = 0; i < s.length(); i++) {
   intArray[i] = s.charAt(i) - '0';
}
System.out.println(Arrays.toString(intArray));

Try this :

public static void main(String args[]){
String sTest = "1234";
int n = sTest.length();
List<Integer> list = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i++){

    int code = Integer.parseInt(sTest.substring(i, i+1));
    list.add(code);
    System.out.println(code);
}
System.out.println(list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM