USING JAVA
Consider the following methods:
StringBuilder has a method append(). If we run:
StringBuilder s = new StringBuilder();
s.append("abc");
The text in the StringBuilder is now "abc"
Character has static methods toUpperCase() and toLowerCase(), which
convert characters to upper or lower case. If we run Character x =
Character.toUpperCase('c');, x is 'C'.
Character also has a static isAlphabetic() method, which returns
true if a character is an alphabetic character, otherwise returns
false.
You will also need String's charAt() method, which returns the
character at a given index in the String. For example,
"Godzilla".charAt(1) returns 'o'.
Write an application as follows:
public static String getNonAlpha() takes a String as a parameter,
builds a StringBuilder consisting of only the nonalphabetic
characters in the String, and returns a String based on the
StringBuilder (eg, sb.toString())
public static String getUpper() takes a String, builds a
StringBuilder of the upper case versions of all the alphabetic
characters in the String, and returns a String based on the
StringBuilder.
Write JUnit tests to verify that the above methods are correct
import static org.junit.Assert.assertEquals;
public class StringOperations {
public static void main(String[] args) {
// Write JUnit tests to verify that
the above methods are correct
assertEquals("@324!",
getNonAlpha("Test@324!"));
assertEquals("TEST@324",
getUpper("Test@324"));
}
// public static String getNonAlpha() takes a String as
a parameter,
// builds a StringBuilder consisting of only the
nonalphabetic characters in the String,
// and returns a String based on the StringBuilder (eg,
sb.toString())
public static String getNonAlpha(String str) {
StringBuilder sb = new
StringBuilder();
for(int
i=0;i<str.length();i++)
if(!Character.isAlphabetic(str.charAt(i)))
sb.append(str.charAt(i));
return sb.toString();
}
// public static String getUpper() takes a String,
builds a StringBuilder of the upper case
// versions of all the alphabetic characters in the
String, and returns a String based on the StringBuilder.
public static String getUpper(String str) {
StringBuilder sb = new
StringBuilder();
for(int
i=0;i<str.length();i++)
sb.append(Character.toUpperCase(str.charAt(i)));
return sb.toString();
}
}
Get Answers For Free
Most questions answered within 1 hours.