Reputation: 393
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 ?
Upvotes: -1
Views: 162
Reputation:
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);
}
Upvotes: 0
Reputation: 24423
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)));
}
Upvotes: 1
Reputation: 37023
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));
Upvotes: 0
Reputation: 11859
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));
}
Upvotes: 0
Reputation: 5868
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.
Upvotes: 0