# 怎么将一串数字拆分成单个数字？

LazyCat2222 2009-06-15 10:45:53

...全文
5196 9 打赏 收藏 举报

9 条回复

``````public class Test5 {

public static void main(String[] args) {
String[] strs = {
"12347890", "00012350", "00000", "00001000"
};

System.out.println("convert1:");
for(int i = 0; i < strs.length; i++) {
int[] nums = convert1(strs[i]);
System.out.printf("  %-15s %s%n", strs[i], Arrays.toString(nums));
}

System.out.println("\nconvert2:");
for(int i = 0; i < strs.length; i++) {
int[] nums = convert2(strs[i]);
System.out.printf("  %-15s %s%n", strs[i], Arrays.toString(nums));
}
}

public static int[] convert1(String strNum) {
String str = preProcess(strNum);
int[] nums = new int[str.length()];
for(int k = 1, num = Integer.parseInt(str); num > 0; k++, num /= 10) {
nums[nums.length - k] = num % 10;
}
return nums;
}

public static int[] convert2(String strNum) {
String str = preProcess(strNum);
int[] nums = new int[str.length()];
char[] chs = str.toCharArray();
for(int i = 0; i < chs.length; i++) {
nums[i] = chs[i] - '0';
}
return nums;
}

private static String preProcess(String strNum) {
if(strNum == null || strNum.length() == 0 || !strNum.matches("\\d+")) {
throw new IllegalArgumentException("number format error!");
}
// 去掉前面的 0
return strNum.replaceAll("^0+(\\d+)", "\$1");
}
}``````
• 打赏
• 举报

xfzhuhan 2009-06-15
``````String  str = "abcdefg";
char temp [] = new char[str.length()];
for(int i=0;i<str.length();i++){
temp[i] = str.charAt(i);
System.out.println(temp[i]);
}``````
• 打赏
• 举报

xnjnmn 2009-06-15
``````
public class TestString {
public static char[] getString(String s){

return s.toCharArray();
}
public static void main(String[] args) {
char[] cs=	getString("12345678");
for (int i = 0; i < cs.length; i++) {
System.out.println(cs[i]);
}

}
}

``````

``````

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<script type="text/javascript"><!--
function splitString(){
var name = document.getElementById("name").value;
var nameArray=new Array([name.length]);
for(var i = 0;i<name.length;i++){
nameArray[i]=name.charAt(i);
//此打印出来
//return nameArray;
}
}

</script>

<body>
<input type="text" id="name" value="12dfdf5678"/>
<br>
<input type="button" onclick="splitString()" value="test"/>
</body>
</html>
``````
• 打赏
• 举报

LazyCat2222 2009-06-15

• 打赏
• 举报

nnb200890 2009-06-15
up!
• 打赏
• 举报

``````
public static void main(String[] args) throws Exception
{
String a = "1234567";
char b[] = a.toCharArray();
for(int i=0;i<b.length;i++)
{
String c = b[i]+"";
int d = Integer.parseInt(c);
System.out.println(d);
}
}
``````
• 打赏
• 举报

baishengjie 2009-06-15
public class GetNumber {

public static char[] getChar(String s){
return s.toCharArray();
}

public static void main(String[] args){
String s = "12345678";
char[] c = getChar(s);
}

}
• 打赏
• 举报

wangljgood 2009-06-15
[Quote=引用 1 楼 kaisa316 的回复:]
toCharArray()
[/Quote]

• 打赏
• 举报

kaisa316 2009-06-15
toCharArray()
• 打赏
• 举报

6.2w+

Java 2 Standard Edition

2009-06-15 10:45