Working with Strings
The Aims
This lab will introduce you to using the Java string classes.
Manipulating Text
-
Create a new Java class called "TestStrings" with a main method. Each of the following questions can be completed in the main method.
-
Create a String called filename with the value "example.doc", change the value to "example.bak".
-
Input two Strings and test them see if they are equal. If they are not equal show which of them lexicographically further forward (in the dictionary!).
-
Find the number of times "ow" occurs in "the quick brown fox swallowed down the lazy chicken"
-
Check to see whether a given string is a palindrome (eg "Live not on evil")
Click here to see the sample solution
class TestStrings {
public static void main(String[] args) {
String filename = "example.doc";
filename = "example.bak";
String one = "Hello";
String two = "Goodbye";
if (one.equals(two)) {
System.out.println("The two strings are equal.");
}
else if (one.compareTo(two) < 0) {
System.out.println(one + " comes before " + two);
}
else {
System.out.println(two + " comes before " + one);
}
String phrase = "the quick brown fox swallowed down the lazy chicken";
// Count occurrences of "ow"
int countOfOw = 0;
int index = phrase.indexOf("ow");
while (index != -1) {
countOfOw++;
index = phrase.indexOf("ow", index + 1);
}
System.out.println ("ow occurs " + countOfOw + " times in "+ phrase);
String text = "Live not on evil";
text = text.replaceAll(" ", "").toLowerCase();
String reversed = new StringBuilder(text).reverse().toString();
if (text.equals(reversed)) {
System.out.println(text + " is a palindrome.");
} else {
System.out.println(text + " is not a palindrome.");
}
}
}