HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Getting the lengths of each word in its String parameter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theeachgettingitswordlengthsstringparameter

Problem

Is this a smart method?

public static ArrayList getWordLengths( String s )
{

    String str = " " + s + " ";

    ArrayList list = new ArrayList();

    for ( int i = 0; i < str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            for ( int j = i+1; j < 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.

Solution

//only allowed to use length and charAt from string class
public static ArrayList getWordLengths( String s )
{
    String str = s + " ";

    ArrayList list = new ArrayList();

    int count = 0;

    for ( int i = 0; i < 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.

Code Snippets

//only allowed to use length and charAt from string class
public static ArrayList<Integer> getWordLengths( String s )
{
    String str = s + " ";

    ArrayList<Integer> list = new ArrayList<Integer>();

    int count = 0;

    for ( int i = 0; i < str.length(); i++ )
    {
        if ( str.charAt(i) == ' ' )
        {
            list.add(count);
            count = 0;   
        }
        else
        {
            count++;
        }
    }
    return list;        
}
[4, 2, 6, 4]

Context

StackExchange Code Review Q#74722, answer score: 2

Revisions (0)

No revisions yet.