简体   繁体   English

字符串到整数数组的转换

[英]String to Integer array conversion

I need to add values into an int array. 我需要将值添加到int数组中。

    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. 我想知道如何将我的字符串输出值反复转换为int数组。

Input: 23.45.1.34 输入: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. 我正在上面的行中将int添加到单个int值,但是如果我需要将int元素添加到数组中,就像推入向量(C ++ STL)一样,我将无法执行。

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 . 当您不知道要存储在数组中的数据集的大小时,应该使用java.util.List<E>的实现,例如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. 然后,如有必要,可以使用List#toArray将列表转换为数组。

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. 我将使用myString.split("\\\\.")返回一个String[] ,创建一个相等大小的int[] ,然后将每个String解析为一个int而不是使用分词器。 Also you could know the size of placeHolders by counting '.'s in the string (eg, myString.replaceAll("[^\\\\.]", "").length() ) (obviously add one to that number). 您也可以通过计算字符串中的'。'来知道placeHolders的大小(例如, myString.replaceAll("[^\\\\.]", "").length() )(显然要在该数字上加上一个)。

I assume your input string is input . 我假设您的输入字符串是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++. 您可以使用ArrayList<Integer> ,它与c ++中的vector相似。 add to it using aList.add(num); 使用aList.add(num);添加到它

if you want an array you can at the end use the toArray method. 如果需要数组,最后可以使用toArray方法。

Integer[] arr = aList.toArray(new Integer[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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