-1

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 ?

5 Answers 5

1

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)));
}
Sign up to request clarification or add additional context in comments.

3 Comments

why you need to convert to char array, if you could access every character from charAt api?
That's just another approach, you wouldn't need a char array but you'd need to use a counter in the for loop.
Yeah counter memory wise wont be expensive and internally toCharArray will create a new cloned copy of your characters within the String. So rather its not efficient and is not best in terms of memory.
0

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

Comments

0

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.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.