開發JAVA程式設計中字串分割的兩種方法(轉)

BSDLite發表於2007-08-16
開發JAVA程式設計中字串分割的兩種方法(轉)[@more@]方法1:採用String的split,驗證程式碼如下:
import java.util.Arrays;
public class TestSplit {
public static void main(String[] args) {
String orignString = new String("5,8,7,4,3,9,1");
String[] testString = orignString.split(",");
int[] test = { 0, 0, 0, 0, 0, 0, 0 };
//String to int
for (int i = 0; i < testString.length; i++) {
test = Integer.parseInt(testString);
}
//sort
Arrays.sort(test);
//asc sort
for (int j = 0; j < test.length; j++) {
System.out.println(test[j]);
}
System.out.println("next ");
// desc
for (int i = (test.length - 1); i >= 0; i--) {
System.out.println(test);
}
}
}
方法2:採用StringTokenizer

import java.util.Arrays;
import java.util.StringTokenizer;
public class SplitStringTest {
public static void main(String[] args) {
String s = new String("5,8,7,4,3,9,1");
int length = s.length();
//split s with ","
StringTokenizer commaToker = new StringTokenizer(s, ",");
String[] result = new String[commaToker.countTokens()];
int k = 0;
while (commaToker.hasMoreTokens()) {
result[k] = commaToker.nextToken();
k++;
}
int[] a = new int[result.length];
for (int i = 0; i < result.length; i++) {
a = Integer.parseInt(result);
}
//sort
Arrays.sort(a);
//asc sort
for (int j = 0; j < result.length; j++) {
System.out.println(a[j]);
}
}
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10617542/viewspace-962182/,如需轉載,請註明出處,否則將追究法律責任。

相關文章