title: Substring manipulation in Java - Find the longest word made from the other words
body: <p>I need to read the contents from a file and find the longest word that can be formed from the other words present in the file. The words in the file are space separated. For example :</p>
  
  <p>Input from file :</p>
  
  <pre><code>This is example an anexample Thisisanexample Thisistheexample
  </code></pre>
  
  <p>Output :</p>
  
  <pre><code>Thisisanexample
  </code></pre>
  
  <p><strong>Note :</strong> The longest word formed is <code>Thisisanexample</code> and not <code>Thisistheexample</code> because the word <code>the</code> is not contained as a separate word in the file. </p>
  
  <p>Is this possible by using simple arrays? I have done the following :</p>
  
  <pre><code>try{
          File file = new File(args[0]);  //command line argument for file path
          br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
          String line = null;
          //array for each word
          String[] words = new String[] {}; 
          while ((line = br.readLine()) != null){
              words = line.split("\\s+"); //splitting the string with spaces
          }
          // array to store length of each word
          int[] wordLength = new int[words.length]; 
          for(int i = 0; i &lt; words.length; i++){
              wordLength[i] = words[i].length();
          }
  
          int currLength = 0; //store length of current word
          int maxLength = 0;  //store length of max word
          String maxWord = null;
  
          //checking each word with others at O(n*n) complexity
          for (int i = 0; i &lt; words.length; i++){
              currLength = 0;
              for (int j = 0; j &lt; words.length &amp;&amp; j != i; j++){
                  if (words[i].contains(words[j])){
                      currLength += wordLength[j];
                  }
              }
              System.out.println(currLength);
              if(currLength &gt; maxLength){
                  maxLength = currLength;
                  maxWord = words[i];
              }
          }
          System.out.println(maxWord);
      }
  </code></pre>
  
  <p>But this does not work if there is a substring withing a substring. It will give wrong output for the following input :</p>
  
  <pre><code>This is example an anexample Thisisanexample Thisisanexample2
  </code></pre>
  
  <p>The output should be <code>Thisisanexample</code> but it gives <code>Thisisanexample2</code>.</p>