4: Strings

4.1 Count Words

Write a method that returns the number of words in a String

4.1.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(countWords(s));
4:   *** Output ***
5:  6

4.2 Count the letter ‘e’

Write a method that counts the instances of the letter ‘e’ in a string.

4.2.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(countEs(s));
4:   *** Output ***
5:  3

4.3 Count Alphanumerics

Write a method that returns the number of alphanumeric characters (A-Z, a-z and 0-9) in a string.

4.3.1 Example

1:  String s = "1984 by George Orwell."
2:
3:  System.out.println(countChars(s));
4:   *** Output ***
5:  18

4.4 Reverse String

Write a method that returns a string, reversed

4.4.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  System.out.println(reverse(s));
4:   *** Output ***
5:  woc elprup a was reven I

4.5 Palindromes

Write a method to test if a string is a Palindrome

4.5.1 Example

1:  String sentence = "I never saw a purple cow"
2:  String palindrome = "rotavator"
3:
4:  System.out.println(isPalindrome(sentence));
5:  System.out.println(isPalindrome(palindrome));
6:   *** Output ***
7:  False
8:  True

4.6 More Palindromes

Write an improved palindrome method that will disregard spaces, punctuation and case and thus recognise sentences such as “A man, a plan, a canal, Panama!” as a palindrome.

4.6.1 Example

1:  String s = "I never saw a purple cow"
2:  String p = "Rise to vote, Sir!"
3:
4:  System.out.println(isPalindrome(s));
5:  System.out.println(isPalindrome(p));
6:   *** Output ***
7:  False
8:  True

4.7 Remove v*w*ls

Write a method that will replace the vowels in a word with asterisks

4.7.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  star(s)
4:   *** Output ***
5:   * n*v*r s*w * p*rpl* c*w

4.8 Spell Out

Write a method to spell out words so that, for example, This becomes T-H-I-S.

4.8.1 Example

1:  String s = "I never saw a purple cow"
2:
3:  spellOut(s)
4:   *** Output ***
5:  I N-E-V-E-R S-A-W A P-U-R-P-L-E C-O-W

4.9 Substitution Cipher

In a simple substitution cipher, A =1 , B=2, C=3 etc. Write a method that encodes a sentence using this cipher

4.9.1 Example

1:  String s = "Hello World"
2:
3:  encode(s)
4:   *** Output ***
5:  8,5,12,12,15 23,15,18,12,4

4.10 Decoder

Write a decoder method for your substitution Cipher

4.10.1 Example

1:  String s = "9 14,5,22,5,18 19,1,23 1 16,21,18,16,12,5 3,15,23"
2:
3:  decode(s)
4:   *** Output ***
5:  i never saw a purple cow

Leave a Comment