字符串分割的两种方法
2008-01-05 08:37:51 来源:WEB开发网方法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[i] = Integer.parseInt(testString[i]);
}
//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[i]);
}
}
}
方法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[i] = Integer.parseInt(result[i]);
}
//sort
Arrays.sort(a);
//asc sort
for (int j = 0; j < result.length; j++) {
System.out.println(a[j]);
}
}
}
- ››字符串格式化工具
- ››分割窗口后如何限制分割条的移动范围
- ››字符串近似匹配算法
- ››方法 (Array)
- ››方法和作用域中的内部类
- ››方法调用的绑定
- ››字符串分割的两种方法
- ››字符串类数据列类型(参考)
- ››分割图像的方法
- ››字符串的一些操作
- ››字符串中文的问题
- ››字符串中包含双引号
更多精彩
赞助商链接