• 热门专题

JAVA字符串分割的两种方法

作者:佚名  发布日期:2011-07-19 18:45:32
Tag标签: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]);
    
      }
    
      }
    
      }
    
    
About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规