Showing posts with label Counting number of spaces at the beginning of the string JAVA. Show all posts
Showing posts with label Counting number of spaces at the beginning of the string JAVA. Show all posts

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;
    }