Getting the lengths of each word in its String parameter Is this a smart method?

public static ArrayList&lt;Integer&gt; getWordLengths( String s )
{

    String str = " " + s + " ";

    ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();

    for ( int i = 0; i &lt; str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            for ( int j = i+1; j &lt; str.length() ; j++)
            {
                if ( str.charAt(j) == ' ')
                {
                    list.add( j - i - 1 );
                    j = str.length();
                }
            }
        }
    }
    return list;        
}


Sample output:



System.out.println( getWordLengths("This is really easy")); 

[4, 2, 6, 4]


so it worked.

We are only allowed to use length and charAt from the String class.
//only allowed to use length and charAt from string class
public static ArrayList&lt;Integer&gt; getWordLengths( String s )
{
    String str = s + " ";

    ArrayList&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;();

    int count = 0;

    for ( int i = 0; i &lt; str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            list.add(count);
            count = 0;   
        }
        else
        {
            count++;
        }
    }
    return list;        
}


Output:

[4, 2, 6, 4]


As long as the length and charAt limitations only apply to string methods and not to use of a List this should be fine.  Just because you need to count more than one thing doesn't mean you need more than one loop.