Java Array Max Value maxCommonLeadingWhitespaceForAll(String[] strings)

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

Description

Determine the maximum number of common leading whitespace characters the strings share in the same sequence.

License

BSD License

Parameter

Parameter Description
strings String[]

Return

int

Declaration

public static int maxCommonLeadingWhitespaceForAll(String[] strings) 

Method Source Code

//package com.java2s;
/**/*from   w w w.j av  a  2  s.c om*/
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */

public class Main {
    /**
     * Determine the maximum number of common leading whitespace characters
     * the strings share in the same sequence. Useful for determining how
     * many leading characters can be removed to shift all the text in the
     * strings to the left without misaligning them.
     * 
     * @param strings String[]
     * @return int
     */
    public static int maxCommonLeadingWhitespaceForAll(String[] strings) {

        int shortest = lengthOfShortestIn(strings);
        if (shortest == 0)
            return 0;

        char[] matches = new char[shortest];

        String str;
        for (int m = 0; m < matches.length; m++) {
            matches[m] = strings[0].charAt(m);
            if (!Character.isWhitespace(matches[m]))
                return m;
            for (int i = 0; i < strings.length; i++) {
                str = strings[i];
                if (str.charAt(m) != matches[m])
                    return m;
            }
        }

        return shortest;
    }

    /**
     * Return the length of the shortest string in the array.
     * If any one of them is null then it returns 0.
     * 
     * @param strings String[]
     * @return int
     */
    public static int lengthOfShortestIn(String[] strings) {

        int minLength = Integer.MAX_VALUE;

        for (int i = 0; i < strings.length; i++) {
            if (strings[i] == null)
                return 0;
            minLength = Math.min(minLength, strings[i].length());
        }

        return minLength;
    }
}

Related

  1. maxArray(double[] input)
  2. maxArray(int[] arr)
  3. maxBetween(int[] arr1, int[] arr2)
  4. maxbits(int[] i, int pos, int length)
  5. maxbits32(int[] i, int pos)
  6. maxcount(int[] vals, int max, int maxcount)
  7. maxDblArrayValue(int npts, double[] dbls)
  8. maxdex(float... values)
  9. maxdiffbits(int initoffset, int[] i, int pos, int length)