Lesson 10, String Manipulation, Homework Questions

Q1

Given the following two program instructions:

var s1 = "The owl and the pussy cat", s2 = "Hickory Dickory Dock";
var s3 = s1 + s2;

What is returned by each of the following method calls?

s3.substring(10, 20) s1.indexOf("pussy")
s3.substring(15, 50) s2.indexOf("Dockery")
s1.substring(17) s3.indexOf(" ",30)
s2.charAt(12) s3.charAt(s2.length)
s3.length s1.charAt(23 - s1.length % 7)

Q2

What's wrong with the following statement? How would you correct the error without changing the contents of the string?

a = "The answer was "six" not "seven", you idiot!";

Q3

Suppose you had the following two commands, operating on a string variable passage, and following directly on from one another:

passage = passage.replace("a","b");
passage = passage.replace("b","a");

The second statement appears to undo the effect of the first, so if there are no intervening instructions, they should cancel each other out. Is this the case, or is it possible that the variable passage is not returned to its initial condition?

Q4

Write a program which asks the user for a piece of text as an input and a word to be blanked out with *** signs. It should then display the text with all occurrences of the word blanked out.

Q5

The split() method can be used to split a sentence into words by recognising the space as a word separator. What happens if you give it a string which contains two or more spaces next to each other? Does it treat those spaces as surrounding words which contain no characters (i.e. words of 0 length), or does it recognise that more than one space can be used as a separator between words? Write a program that will test this idea.

Q6

A palindrome is a word or phrase which is the same when spelled backwards, such as the words "level" or "deified". Write a program which asks the user for an input and then informs the user whether that input is a palindrome or not. You may find that the best way to do it is using the charAt() method.

Q7

Caesar put all his messages into code as follows: He replaced all the letter As in the plain message with Cs in the coded one, all the letter Bs in the plain message with Ds in the coded one, Cs in the plain message with Es in the coded one etc. All the letter Ys in the plain message were replaced by As in the coded message, and all the letter Zs in the plain message were replaced by As in the coded one.

Write a program which takes a plain English message, encodes it using Caesar's cipher, and then displays it on the screen. For good measure, you should write another program which takes messages coded in this way and produces the plain English version.

Q8

Write a program which counts the vowels in a piece of text.