服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 高级技术 > 设计模式 > 查看文档

开发java编程中字符串分割的两种方法

方法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]);
  }
 }
}

扫描关注微信公众号