2016-03-21 16 views
1

Aşağıdaki programın amacı, "/"" " ve ":" ayırıcıları sayesinde kaynak dizesini sınırlandırmaktır. Beklenen çıktı, 20 03 2016 17 30 ancak son öğeyi atlayarak yalnızca 20 03 2016 17 verir. Belki bazı teker teker hata?Java dize sınırlama programında birebir hata

public static void main(String[] args) { 
    String source = "20/03/2016:17:30"; 
    String sep = "/:"; 
    String[] result = new String[5]; 
    String str = ""; 
    int index = 0; 

    for (int sourcePos = 0; sourcePos < source.length(); sourcePos++) { 
     int compt = 0; 

     for (int sepPos = 0; sepPos < sep.length(); sepPos++) { 
      if (source.charAt(sourcePos) == sep.charAt(sepPos)) compt++; 
     } 

     if (compt > 0) { 
      result[index] = str; 
      System.out.print(" " + result[index]); 

      if (index < result.length) 
       index++; 
      else 
       break; 

      str = ""; 
     } else { 
      str = str + source.charAt(sourcePos); 
     } 
    } 
} 

cevap

4

Sadece regex kullanabilirsiniz:

Kodunuzdaki gelince
String[] result = source.split("/|:"); 

son kez if (compt > 0) ulaşmadan, bir tanesinde kapalı olmasının nedeni ana for döngü sonlandırılır olmasıdır. Başka bir deyişle, son str'u eklemeden önce sourcePos < source.length(), false'dur.

Çok şey gibi olabilir: Eğer regex olmadan bir çözüm istedi yana

for (int sourcePos = 0; sourcePos < source.length() ; sourcePos++) { 
    boolean compt = false; 

    for (int sepPos = 0; sepPos < sep.length(); sepPos++) { 
     if (source.charAt(sourcePos) == sep.charAt(sepPos)) { 
      compt = true; 
      break; 
     } 
    } 

    if (compt) { 
     result[index] = str; 
     index++; 
     str = ""; 
    } 

    else if(sourcePos == source.length()-1) { 
     result[index] = str + source.charAt(sourcePos); 
    } 

    else { 
     str = str + source.charAt(sourcePos); 
    } 
} 
+0

off-by-one hata açıklaması için teşekkürler :) – loukios

+0

Bu yorumu eklemek için üzgünüz, ama çıktı olarak kodunuzla başka bir tür bir-off-one hatası gibi görünüyor 03/2016: 16 "yerine" 20 03 2016 17 30 ". Bir fikrin neden? – loukios

0

(alıntı "... ama regex olmadan bunu yapmak istemedim") diğer

public static void main(String[] args) { 
    String source = "20/03/2016:17:30"; 
    String result = ""; 
    String before = ""; 
    for (int sourcePos=0; sourcePos < source.length(); sourcePos ++) { 
     if (java.lang.Character.isDigit(source.charAt(sourcePos))) { 
      result += before + source.charAt(sourcePos); 
      before = ""; 
     } else { 
      before = " "; // space will be added only once on next digit 
     } 
    } 
    System.out.println(result); 
} 

şey Birden fazla karakter olsa bile, bir basamaktan bir ayırıcı sayılır.