title: java.lang.StringIndexOutOfBoundsException: String index out of range: 1
body: <p>I'm learning Java and I don't know what is wrong here. Why is this error happening? I don't see anything wrong and that was actually working until when I wrote the line "count = 0" before the second "for" loop.</p>
  
  <p>That is the error: java.lang.StringIndexOutOfBoundsException: String index out of range: 1</p>
  
  <p>That's the line where the error is happening: </p>
  
  <pre><code>if(mots.get(j).startsWith(searchPhrase.substring(0,1))){
  </code></pre>
  
  <p>Here is the entire code:</p>
  
  <pre><code>import java.util.*;
  
  public class Test {
      public static void main(String[] args) {
          List&lt;String&gt; mots = new ArrayList&lt;&gt;();
          List&lt;String&gt; saida = new ArrayList&lt;&gt;();
          mots.add("un");
          mots.add("deux");
          mots.add("trois");
          String searchPhrase = "aaasdeuxctsundesle";
          int count = 0;
          int countAnula = 0;
          int azul = 0;
          String anula = "-"; //Tem que fazer cast para char depois
          String frase = searchPhrase;
          for (int i = 0; i &lt; frase.length(); i++) {
              count = 0;
              for (int j = 0; j &lt; mots.size(); j++) {
                  if (mots.get(j).startsWith(searchPhrase.substring(0,1))) {
                      for (int t = 0; t &lt; mots.get(j).length(); t++) {
                          if (searchPhrase.charAt(t) == mots.get(j).charAt(t)) {
                              azul ++;
                          } else {
                              break;
                          }
                      }
                      if (azul == mots.get(j).length()) {
                          saida.add(mots.get(j)); 
                          searchPhrase = searchPhrase.substring(mots.get(j).length());
                          j = 0;
                          azul = 0;
                      } else {
                          searchPhrase = searchPhrase.substring(1);
                          saida.add(anula);
                          j = 0;
                          azul = 0;
                      }
                  } else {
                      count ++;
                  }        
              } 
              if (count == mots.size()) {
                  searchPhrase = searchPhrase.substring(1);
                  saida.add(anula);
                  count = 0;
              }   
          }
          for (int g = 0; g &lt; saida.size(); g++) {
              System.out.println(saida.get(g)); 
          }
      }
  }
  </code></pre>