Java面向对象-String类作业一字符串转数组
将字符串“1,3,5,7,9”,转换成数组,数组元素是整数元素1,3,5,7,9 ;
思路:
首先我们需要定义一个新的整型数组来存储元素,但是定义数组需要知道数组的长度;
我们先遍历字符串,统计出数字的个数,即数组的长度,这样我们就能实例化数组了;
然后我们就是再次遍历字符串,把数组挨个的存储到数组中;
我们给下参考代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package
com.java1234.chap03.sec08;
public
class
Test {
public
static
void
main(String[] args) {
String str=
"1,3,5,7,9"
;
int
shuZi=
0
;
for
(
int
i=
0
;i<str.length();i++){
if
(str.charAt(i)!=
','
){
shuZi++;
}
}
int
[]arr=
new
int
[shuZi];
int
j=
0
;
for
(
int
i=
0
;i<str.length();i++){
if
(str.charAt(i)!=
','
){
arr[j]=Integer.parseInt(str.charAt(i)+
""
);
j++;
}
}
for
(
int
a:arr){
System.out.print(a+
" "
);
}
}
}
|
注意:这里需要使用int的包装类的parseInt方法 把字符串转成int类型;