简体   繁体   English

在java中将String转换为int数组

[英]Convert String to int array in java

I have one string我有一根绳子

String arr= "[1,2]";

ie "[1,2]" is like a single string即“[1,2]”就像一个字符串

How do convert this arr to int array in java如何在java中将此arr转换为int数组

String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");

int[] results = new int[items.length];

for (int i = 0; i < items.length; i++) {
    try {
        results[i] = Integer.parseInt(items[i]);
    } catch (NumberFormatException nfe) {
        //NOTE: write something here if you need to recover from formatting errors
    };
}

Using Java 8's stream library, we can make this a one-liner (albeit a long line):使用 Java 8 的流库,我们可以使它成为一行(虽然很长):

String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
    .map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. substring删除括号, split分隔数组元素, trim删除数字周围的任何空格, parseInt解析每个数字,我们将结果转储到数组中。 I've included trim to make this the inverse of Arrays.toString(int[]) , but this will also parse strings without whitespace, as in the question.我已经包含了trim以使其与Arrays.toString(int[])相反,但这也将解析没有空格的字符串,如问题所示。 If you only needed to parse strings from Arrays.toString , you could omit trim and use split(", ") (note the space).如果您只需要从Arrays.toString解析字符串,则可以省略trim并使用split(", ") (注意空格)。

    final String[] strings = {"1", "2"};
    final int[] ints = new int[strings.length];
    for (int i=0; i < strings.length; i++) {
        ints[i] = Integer.parseInt(strings[i]);
    }

It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (eg http://json.org/java/ ) to parse it:它看起来像 JSON - 根据具体情况,它可能有点矫枉过正,但您可以考虑使用 JSON 库(例如http://json.org/java/ )来解析它:

    String arr = "[1,2]";

    JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");

    int[] outArr = new int[jsonArray.length()]; 

    for(int i=0; i<jsonArray.length(); i++) {
        outArr[i] = jsonArray.getInt(i);
    }

Saul's answer can be better implemented splitting the string like this:扫罗的答案可以更好地实现拆分字符串,如下所示:

string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");

try this one, it might be helpful for you试试这个,它可能对你有帮助

String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();

You can do it easily by using StringTokenizer class defined in java.util package.您可以使用 java.util 包中定义的 StringTokenizer 类轻松完成。

void main()
    {
    int i=0;
    int n[]=new int[2];//for integer array of numbers
    String st="[1,2]";
    StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
    String s[]=new String[2];//for String array of numbers
     while(stk.hasMoreTokens())
     {
        s[i]=stk.nextToken();
        n[i]=Integer.parseInt(s[i]);//Converting into Integer
       i++;
     }
  for(i=0;i<2;i++)
  System.out.println("number["+i+"]="+n[i]);
}

Output :-number[0]=1 number[1]=2输出:-number[0]=1 number[1]=2

    String str = "1,2,3,4,5,6,7,8,9,0";
    String items[] = str.split(",");
    int ent[] = new int[items.length];
    for(i=0;i<items.length;i++){
        try{
            ent[i] = Integer.parseInt(items[i]);
            System.out.println("#"+i+": "+ent[i]);//Para probar
        }catch(NumberFormatException e){
            //Error
        }
    }

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.在紧密循环或移动设备上,通过短期String对象生成大量垃圾并不是一个好主意,尤其是在解析长数组时。

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers.我的答案中的方法解析数据时不会产生垃圾,但它没有优雅地处理无效数据,也无法解析负数。 If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.如果您的数据来自不受信任的来源,您应该进行一些额外的验证或使用其他答案中提供的替代方法之一。

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet countOccurrences 的实现被 John Skeet 无耻地偷走了

String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

If you prefer an Integer[] instead array of an int[] array:如果您更喜欢Integer[]而不是int[]数组的数组:

Integer[]整数[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

int[]内部[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()

This works for Java 8 and higher.这适用于 Java 8 及更高版本。

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

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