Friday 13 July 2012

Counting number of spaces at the beginning of the string JAVA

Count the number of spaces at the beginning of a string in a Java program
   
private int countSpaces(String s)
    {
        int spaceCount = 0;
        if ( s == null || s.trim().isEmpty() )
            return spaceCount;

        int length = s.length();
        for ( int i = 0; i < length; i++ )
        {
            if ( s.charAt(i) == ' ' )
                spaceCount++;
            else
                break;
        }
        return spaceCount;
    }

No comments:

Post a Comment