分割字符串新

旧的分割方法出了一个问题,就是当字符串为"aa;bb;  cc;c dd /csfsd /" 这样的一个字符串按照/分割后,数组的大小应该为2才对,最后一个为""应该去掉,下面加一个判断

private String[] split(String str, char ch) {
     
  if (str.indexOf((ch + "").trim()) <= 0) {
   return null;
  }
  int a = 0; // 存放ch的数量
  for (int i = 0; i < str.length(); ++i)
   if (ch == str.charAt(i))
    ++a;
  String[] arr =null;
  if(str.charAt(str.length()-1)==ch){
   arr = new String[a];
  }else {
   arr = new String[a];
  }
  
  Integer[] arrint = new Integer[a];
  int b = 0; // 增量,实现同步
  for (int i = 0; i < str.length(); ++i)
   if (ch == str.charAt(i)) {
    arrint[b] = Integer.valueOf(i + 1);
    ++b;
   }
  int begin = 0;
  int ab = 0; // 增量
  for (int i = 0; i < arrint.length; ++i) {
   arr[ab] = str.substring(begin, arrint[i].intValue() - 1);
   begin = arrint[i].intValue();
   ++ab;
  }
  //判断字符是否是字符串的最后一个符号
  if(str.charAt(str.length()-1)==ch){
   return arr;
  }else{
   arr[(arr.length - 1)] = str.substring(arrint[(arrint.length - 1)]
     .intValue());
  }
  return arr;
 }

这样就没有问题了

当中间有多个空格,合并为一个空格用.replaceAll("\s{1,}", " "),再去掉左右两边的空格trim(),

每个字符可用

String str;

str.replaceAll("\s{1,}", " ").trim();

的方式处理。