Docsity

Solution to Quiz 6 in CMSC 131 Fall 2004 - String Manipulation - Prof. Nelson Padua-Perez, Quizzes of Computer Science

Toggle sidebar
bg1
CMSC 131 Fall 2004 Quiz 6 Solution
One possible solution
The method count runs through all the elements of the string array str and compares each
against the length. It updates a counter ct for each string it finds that satisfies the
condition.
The method lessOrEqual first calls count() to determine the number of elements that
satisfy the condition, and then allocates an array result with this many elements. It
maintains an index nxt, which points to the next available element of this array.
Whenever we find an element that satisfies the length condition, we store it in the next
position of result and increment nxt.
public class Util {
public static int count( String[] str, int len ) {
int ct = 0;
for ( int i = 0; i < str.length; i++ )
if ( str[i].length() <= len ) ct++;
return ct;
}
public static String[] lessOrEqual ( String[] str, int len ) {
int ct = count( str, len );
String[] result = new String[ct]; // allocate result array
int nxt = 0; // next available position
for ( int i = 0; i < str.length; i++ ) {
if ( str[i].length() <= len ) {
result[nxt++] = new String( str[i] );
}
}
return result;
}
}

Partial preview of the text

Download Solution to Quiz 6 in CMSC 131 Fall 2004 - String Manipulation - Prof. Nelson Padua-Perez and more Quizzes Computer Science in PDF only on Docsity!

CMSC 131 Fall 2004 Quiz 6 Solution

One possible solution

The method count runs through all the elements of the string array str and compares each

against the length. It updates a counter ct for each string it finds that satisfies the

condition.

The method lessOrEqual first calls count() to determine the number of elements that

satisfy the condition, and then allocates an array result with this many elements. It

maintains an index nxt, which points to the next available element of this array.

Whenever we find an element that satisfies the length condition, we store it in the next

position of result and increment nxt.

public class Util { public static int count( String[] str, int len ) { int ct = 0; for ( int i = 0; i < str.length; i++ ) if ( str[i].length() <= len ) ct++; return ct; } public static String[] lessOrEqual ( String[] str, int len ) { int ct = count( str, len ); String[] result = new String[ct]; // allocate result array int nxt = 0; // next available position for ( int i = 0; i < str.length; i++ ) { if ( str[i].length() <= len ) { result[nxt++] = new String( str[i] ); } } return result; } }