Reputation: 2285
I need to add values into an int array.
int[] placeHolders[];
Now i do not know the size of the elements to add into this array. I add it while i have input. I want to know how can i convert my string output values into int array repeatedly.
Input: 23.45.1.34
I am using string tokenize on . to get tokens
Value = Integer.parseInt(strtokObject.nextElement().toString());
I am using above line to add int to single int value but if i need to add int elements to array just like push in vector (C++ STL) i am unable to do.
Upvotes: 1
Views: 845
Reputation: 5178
I assume your input string is input
.
So you can do something like this:
String[] inputStrs = input.split("\\.");
and
//Do a while loop
placeholder[i] = Integer.ParseIne(inputStrs[i]);
Upvotes: 1
Reputation: 771
You can use ArrayList<Integer>
which is similar to vector in c++.
add to it using aList.add(num);
if you want an array you can at the end use the toArray
method.
Integer[] arr = aList.toArray(new Integer[0]);
Upvotes: 0
Reputation: 5674
I'd use myString.split("\\.")
to return a String[]
, create an equal size int[]
, then parse each String to an int rather than use a tokenizer. Also you could know the size of placeHolders
by counting '.'s in the string (e.g., myString.replaceAll("[^\\.]", "").length()
) (obviously add one to that number).
Upvotes: 2
Reputation: 28687
When you don't know the size of a data set to be stored in an array, you should use an implementation of java.util.List<E>
such as ArrayList
.
ArrayList<Integer> placeHolderList = new ArrayList<Integer>();
int value = Integer.parseInt(strtokObject.nextElement().toString());
placeHolderList.add(value); // adds the int to the underlying array
You can then use List#toArray to convert your list into an array if necessary.
Upvotes: 2
Reputation: 115328
String str = "23.45.1.34";
String sarr = str.split("\\.");
int[] result = new int[sarr.length];
for (int i = 0; i < sarr.length; i++) {
result[i] = Integer.parseInt(s);
}
Upvotes: 5