Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Exercise 21-Strings Using the given project Strings, complete each section in th

ID: 3842027 • Letter: E

Question

Exercise 21-Strings Using the given project Strings, complete each section in the class YourCode by using the methods specified in each exercise (you may declare additional variables). No need to askthe user to enter values; use the variables that are already declared in the method. The class Testing already has testing cases to test your code. You simply need to compile and execute either the main method oreach section of this class. Details about methods of the class String can be found in the String lecture slides. The method length0 requires no parameters and it returns the length of the string as an int. Folder name: A170 E21 Your LastName_YourFirstName Part A. HALF A STRING Given a string strl of even length, print out the first half. Methods to use substring0, length0 Testing cases: Woo Hello There Hello abcdef abc 0123456789 01234 Part B. WITHOUT ENDS Given a string strl print out the string without the first and last char. The string length is at least 2. Methods to use: substringl), length0 Testing Hello coding odin od (empty string) Chocolate ittee ex ooho

Explanation / Answer


/**
*
* @author Sam
*/
public class StringFuntions {
    public static void printPartA (String str) {
        int length = str.length(); //records the length of the string
        System.out.println(str.substring(0, length/2)); //extracts the sub string of length half of original
    }
  
    public static void printPartB (String str) {
        int length = str.length();
        String newStr = str.substring(1,length-1); //extracts substring without the 1st char and the last char
        System.out.println(newStr);
    }
  
    public static void printPartC (String str) {
        int length = str.length();
        if (length > 2){
            String prefix = str.substring(0,2); //store the first 2 char
            String suffix = str.substring(2); //store the remaining chars
            System.out.println(suffix+prefix);
        }
        else
            System.out.println(str);
    }
  
    public static void printPartD (String str) {
        int length = str.length();
        int count = 0;
        for (int i=0; i< length-1; i++) //loop iterates over the string
            if (str.substring(i, i+2).equals("hi")) //and matches all possible substring of length 2 with hi
                count ++; //if matches, increase count
        System.out.println(count);
    }
  
}

I hope this code makes sense. If thing you need clarification or having trouble understanding the code, please feel free to comment below. I shall be glad to help you