In: Computer Science
. Write a function in JAVA called shorten that is defined in the class P8 and shortens each element of an array of strings. Every string with more than two characters is cut down to its first two characters. For example, a program that uses the function shorten follows.
public class P8 {
public static void main(String args[]) {
String x[] = {"CSCI", "1", "11", "Queens", "College", "CUNY"};
shorten(x);
for (int i = 0; i < 6; i++) System.out.print(x[i] + " "); // Output: CS 1 11 Qu Co CU System.out.println();
SOLUTION:
CODE:
public class P8
{
/* Method: shorten */
/* shorten the strings which are more than two characters to first
two characters */
public static void shorten(String []x)
{
/* loop through all the strings */
for (int i = 0; i < 6; i++)
{
/* if the length of the string greater than 2 character,
then shorter the string to first 2 characters*/
if(x[i].length() > 2)
{
/* use substring function. start position is 0, end position is 2
*/
x[i] = x[i].substring(0,2);
}
}
}
public static void main (String args[])
{
String x[] = {"CSCI", "1", "11", "Queens", "College", "CUNY"};
shorten (x);
for (int i = 0; i < 6; i++)
System.out.print (x[i] + " "); // Output: CS 1 11 Qu Co
CU
System.out.println ();
}
}
OUTPUT: