题目要求
将字符串数组里的数字读出
如string a[ ]={4,48,52,69}变成int a[]= {4,48,52,69,}
代码展示:
package test;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//测试 仿String.split 功能
String a = "8,10,21,30";
String temp = "";
ArrayList b = new ArrayList();
for (int i = 0; i < a.length() ; ++i) {
if (a.charAt(i) == ',') {
b.add(Integer.parseInt(temp));
temp = "";
} else {
temp += a.charAt(i);
}
}
if (temp.length() > 0) {
b.add(Integer.parseInt(temp));
temp = "";
}
int[] res = new int[b.size()];
for (int i = 0 ;i <res.length ; ++i) {
res[i] =(int)b.get(i);
System.out.printf(res[i] + " ");
}
}
}
或
import java.io.*;
public class Appmain {
public static void main(String args[]) throws IOException
{
String S=new String("8,48,19,36");
int []a=new int[4];
int j=0;
int flag=1;
String S1;
for(int i=0;i<S.length() && flag !=-1;i=0)
{
flag=S.indexOf(',');
if(flag !=-1)
{
S1=S.substring(0,flag);
}
else
{
S1=S;
}
for(int k=0;k<S1.length();k++)
{
char c=S1.charAt(k);
a[j]=a[j]*10+c-'0';
}
j++;
S=S.substring(flag+1,S.length());
}
System.out.println("数组中的元素是:");
for(int i=0;i<4;i++)
{
System.out.println(a[i]);
}
}
}