Java String Collapse collapseStrings(String[] strings)

Here you can find the source of collapseStrings(String[] strings)

Description

Empty out all but the smallest unique strings from the array.

License

Open Source License

Declaration

public static final void collapseStrings(String[] strings) 

Method Source Code

//package com.java2s;
/*/*  ww  w. j  av  a2  s. c om*/
  Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com)
    
  This file is part of the Semantic Discovery Toolkit.
    
  The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
    
  The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Lesser General Public License for more details.
    
  You should have received a copy of the GNU Lesser General Public License
  along with The Semantic Discovery Toolkit.  If not, see <http://www.gnu.org/licenses/>.
  */

public class Main {
    /**
       * Empty out all but the smallest unique strings from the array.
       * (Where emptying out sets the reference to null.)
       * <p>
       * That is, if one string is a substring of another, discard the other.
       * <p>
       * NOTE: this DESTRUCTIVELY modifies the input array's references!
       */
    public static final void collapseStrings(String[] strings) {
        if (strings == null || strings.length < 2)
            return;

        for (int i = 0; i < strings.length - 1; ++i) {
            final String string1 = strings[i];
            if (string1 == null)
                continue;
            final int len1 = string1.length();

            for (int j = i + 1; j < strings.length; ++j) {
                final String string2 = strings[j];
                if (string2 == null)
                    continue;
                final int len2 = string2.length();

                if ((len1 < len2) && (string2.indexOf(string1) >= 0)) {
                    strings[j] = null;
                } else if ((len2 < len1) && (string1.indexOf(string2) >= 0)) {
                    strings[i] = null;
                    break;
                }
            }
        }
    }
}

Related

  1. collapseLines(String message)
  2. collapseMultipleNewlinesToOne(String s)
  3. collapseName(String name)
  4. collapseNewlines(String argStr)
  5. collapseString(String data, String collapse)