2016-03-21 5 views
1

次のプログラムの目的は、区切り文字 " "":"のおかげでソース文字列を区切ることです。予想される出力は20 03 2016 17 30ですが、最後の要素は省略して20 03 2016 17になります。たぶんオフに1つのエラー?Javaの文字列区切りプログラムで1つずつエラーが発生する

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); 
     } 
    } 
} 

答えて

4

あなたは、単にregexを使用することができます。

あなたのコードについては
String[] result = source.split("/|:"); 

あなたが最後にif (compt > 0)に到達する前に、あなたは1でオフになっている理由は、メインforループが終了していることです。つまり、sourcePos < source.length()falseです。最後にstrを追加することができます。

あなたがそうのようなものでした:あなたは正規表現のない解決策を求めているので

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エラーの説明に感謝します:) – loukios

+0

このコメントを少し遅く追加して申し訳ありませんが、あなたのコードに別の種類のオフラインエラーがあります。出力は "20/「20 03 2016 17 30」の代わりに「03/2016:16」と表示されます。どんな考え? – loukios

0

は(引用「...しかし、私は正規表現せずにそれを行うためのもの」)

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); 
} 

他の何か数字が複数の文字であっても、区切り文字はセパレータと見なされます。

関連する問題