String Utilities Implement the following methods Write a me

String Utilities

Implement the following methods:

// Write a method that returns true if s has leading or trailing whitespace, false otherwise

public static boolean needsTrim(String s)

// Write a method that swaps the first three and last four characters of s

public static String swap3For4(String s)

// Write a method that has one String parameter, and returns true if the first half and last half of the parameter are the same ignoring case, and false otherwise. (The name of the method is up to you.)

Use these methods to rewrite the corresponding parts of the String Play program of Unit Strings.

Solution

//StringUtilities.java
import java.util.Scanner;
public class StringUtilities
{
    // method that returns true if s has leading or trailing whitespace, false otherwise
    public static boolean needsTrim(String s)
    {
        String str = s.trim();
        if(str.equals(s))
            return true;
        return false;
    }

    // method that swaps the first three and last four characters of s
    public static String swap3For4(String s)
    {
        return s.substring(s.length() -4) + s.substring(3,s.length() -4) + s.substring(0, 3);
    }

    // method that swaps the first three and last four characters of s
    public static boolean checkEqualSubstring(String s)
    {
        s = s.toLowerCase();
        int len = s.length();
      
        if(s.substring(0, len/2).equals(s.substring(len/2)))
            return true;
      
        return false;
    }

    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.println(\"Enter a string: \");
        String str = scan.nextLine();
      

        if(needsTrim(str))
            System.out.println(\"\ NO trailing spaces in input text\");
        else
            System.out.println(\"\ There are trailing spaces in input text\");

        // remove trailing space
        str = str.trim();
        String result = swap3For4(str);
        System.out.println(\"Swaped string: \" +result);

        // remove spaces in string
        str = str.replaceAll(\"\\\\s+\",\"\");


        if(checkEqualSubstring(str))
            System.out.println(\"First half is equal to the second half of string\");
        else
            System.out.println(\"First half is NOT equal to the second half of string\");

      
    }
}


/*
output:

Enter a string:
abcd abcd

There are trailing spaces in input text
Swaped string: abcdd abc
First half is equal to the second half of string

*/

String Utilities Implement the following methods: // Write a method that returns true if s has leading or trailing whitespace, false otherwise public static boo
String Utilities Implement the following methods: // Write a method that returns true if s has leading or trailing whitespace, false otherwise public static boo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site