将字符串转换为整数数组ex String st ="1 2 3 4 5";进入ar = [1,2,3,4,5] [英] Converting string into array of ints ex String st = "1 2 3 4 5" into ar=[1,2,3,4,5]

查看:114
本文介绍了将字符串转换为整数数组ex String st ="1 2 3 4 5";进入ar = [1,2,3,4,5]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一个字符串,作为整行数字,用空格隔开,即 1 2 3 4 5 .我想将它们转换为整数数组,以便可以操纵它们.但是此代码不起作用.它说不兼容的类型.

I am reading in a string, as an entire line of numbers, separated by spaces, ie ie 1 2 3 4 5. I want to convert them into an array of integers, so that I can manipulate them. But this code doesn't work. It says incompatible types.

String str = br.readLine();
int[] array = new int[4];
StringTokenizer tok = new StringTokenizer(str," ", true);
boolean expectDelim = false;
int i = 0;

while (tok.hasMoreTokens()) {
    String token = tok.nextToken();
    ar[i] = Integer.parseInt(token);
    i++;
}

推荐答案

如果您有 String s ="1 2 3 4 5" ,则可以将其拆分为如下的单独位:

If you have a String s = "1 2 3 4 5" then you can split it into separate bits like this:

String[] bits = s.split(" ");

现在,您必须将它们转换为 int [] :

Now you have to put them into an int[] by converting each one:

int[] nums = new int[bits.length];
int i=0;
for (String s: bits)
    nums[i++] = Integer.parseInt(s);

这将遍历split数组中的每个小字符串,将其转换为整数,然后将其放入新数组中.

This will loop through each of the small strings in the split array, convert it to an integer, and put it into the new array.

这篇关于将字符串转换为整数数组ex String st ="1 2 3 4 5";进入ar = [1,2,3,4,5]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆