如何通过忽略空格来分割字符串

时间:2014-10-01 07:16:34

标签: java

 public class TestBoolean { 

     public static void main(String[] args) { 

         String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999"; 

         String[] b = a.split("999"); 
         for (String c : b) { 
             System.out.println("Value\t:" + c); 
         } 

     } 
 } 

我需要输出

 13131300100 999 
 13131300200 999 
 13131300300 999 
 13131300400 999

7 个答案:

答案 0 :(得分:4)

对于您的示例,您可以将拆分正则表达式更改为以下内容:

String[] b = a.split("\\s(?!999)");

这将匹配:

  1. first \\ s - 空格字符
  2. (?!999) - 未跟随999。
  3. 输出:

    Value   :13131300100 999
    Value   :13131300200 999
    Value   :13131300300 999
    Value   :13131300400 999
    

    正则表达式字符类可以在Pattern

    的文档中找到

答案 1 :(得分:1)

public static void main(String[] args) { 

    String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999"; 

    String[] b = a.split(" "); 
    int len = b.length;
    for (int i = 0; i < len; i=i+2) {
         System.out.println(b[i]+" " + b[i+1]); 
    }

} 

输出

13131300100 999
13131300200 999
13131300300 999
13131300400 999

答案 2 :(得分:0)

你快到了。如果999是您的分隔符,则应将字符串拆分为“999”。

您可以将结果打印为

 public static void main(String[] args) { 

     String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999"; 
     String delimiter = " 999";

     String[] b = a.split(delimiter); 
     for (String c : b) { 
         System.out.println(c.trim() + delimiter); 
     } 

 } 

答案 3 :(得分:0)

您可以在拆分前替换空格

String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999";
a = a.replaceAll(" ","");

答案 4 :(得分:0)

public static void main(String[] args) {

    String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999"; 

    String[] b = a.split(" "); 
    for (int i =0 ;i<b.length;i++) { 
        System.out.println("Value\t:" + b[i]+b[i+1]); 
        i++;
}

试试这个

答案 5 :(得分:0)

   String a = "13131300100 999  13131300200 999 13131300300 999 13131300400 999"; 
    Pattern p = Pattern.compile("(\\s)+");  //handles one or more space
    String[] m = p.split(a);

    for(int i=0; i< m.length-1; i+=2){
        System.out.println(m[i]+" "+m[i+1]);
    }

答案 6 :(得分:0)

这可能符合您的要求

public class Demo { 

 public static void main(String[] args) { 

     String a = "13131300100 999 13131300200 999 13131300300 999 13131300400 999"; 

     StringBuilder myName = new StringBuilder(a);
     int i=0,spacecnt=0;
     while(i!=a.length()){
         if(a.charAt(i)==' '){
             spacecnt+=1;
             if(spacecnt%2==0)
                 myName.setCharAt(i, '\n');
         }
         i++;
     }
     System.out.println(myName);
 } 

}

输出:

13131300100 999
13131300200 999
13131300300 999
13131300400 999