简体   繁体   中英

String to Integer array conversion

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.

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

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.

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 (eg, myString.replaceAll("[^\\\\.]", "").length() ) (obviously add one to that number).

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

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

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