1. Character and String Processing

For storing characters and strings, Java provides the types char, Character, String and StringBuilder. The use of the data types must be practiced because each type has its justification. The exercises help the readers to understand the advantages and disadvantages of each data type.

Prerequisites

  • be able to use API of String and StringBuilder safely

  • recognize when String and StringBuilder is more appropriate

Data types used in this chapter:

1.1. The String class and its properties

String is not only a data type that stands for immutable strings, but the class also provides many methods. If you know the methods and how to use them, you can save yourself a lot of work.

1.1.1. Building HTML elements with simple concatenation ⭐

As a reminder, tags are used in HTML for markup, an example is <strong><em>Emphasized and Italics</em></strong>.

Task:

  1. Write a new method htmlElement(String tag, String body) that encloses a string body with a start and end tag tag and returns it as a new String. There is extra handling:

    • If tag is equal to null or empty ("") then only the body is considered and no start-end tags are written.

    • If body is equal to null then it is considered like a passed empty string.

  2. Write two new methods, strong(String) and emphasized(String) that work in the background with htmlElement(…​) and create a <strong> and <em> respectively.

Example:

  • htmlElement( "strong", "strong is bold" )"<strong>strong is bold</strong>"

  • strong( emphasized( "strong + emphasized" )"<strong><em>strong + emphasized</em></strong>"

  • htmlElement( "span", null )"<span></span>"

  • htmlElement( "", "no" )"no"

  • htmlElement( null, "not strong" )"not strong"

  • htmlElement( null, null )""

Note: There are several restrictions on tag names that a good program could check. For example, tag names may only contain the digits 0 to 9 and upper and lower case letters. These cases can be ignored.

1.1.2. Check safe transmission by doubling characters ⭐

Bamboo Blobfish uses a type-print telegraph to communicate important messages to Bonny Brain. Since every character is crucial, Bamboo sends each character twice in a row for safety.

Check safe transmission by doubling characters

Task:

  • Write a method int isEveryCharacterTwice(String) that checks if each character in the string occurs twice in a row.

    • If the number of symbols is odd, the message is wrong and the method returns 0.

    • If each character occurs twice, the answer is any positive number. ˗ If a character does not occur twice in a row, the method returns the position with the first wrong digit but negated it.

Examples:

  • isEveryCharacterTwice("jjoovveellyynn")1

  • isEveryCharacterTwice("ccapptttaaiinn")-3

  • isEveryCharacterTwice("222")0

  • isEveryCharacterTwice(null)NullPointerException

The fact that a negative index marks certain locations can also be found in the Java library. The Arrays class provides binarySearch(…​), which searches for something in a sorted array, and if the method finds the element, returns the location; if binarySearch(…​) does not find the entry, it returns the negated position where the element could be inserted.

1.1.3. Swap Y and Z ⭐

Captain CiaoCiao types a longer text on his keyboard, and quite late he notices that instead of the English keyboard layout, the German one is activated. Now "y" and "z", or "Y" and "Z" are swapped. The text has to be corrected.

Swap Y and Z

Task:

  1. Create a new class YZswapper.

  2. Set a new static method void printSwappedYZ(String string), which prints a given string to the screen, but prints the letter "y" as "z", "z" as "y", "Y" as "Z" and "Z" as "Y". The point is not to return a string from the method!

  3. Do not write only one variant, but try to program at least two variants. There is, for example, the possibility to check the characters with if-else or with switch-case.

Examples:

  • printSwappedYZ("yootaxz") gives the output zootaxy on the screen and

  • printSwappedYZ("yanthoxzl") gives the output zanthoxyl.

1.1.4. Give defiant answers ⭐

Tony the Defiant is responsible for Captain CiaoCiao’s black market activities, but he gets caught and questioned by the police. To annoy the cops, he repeats everything they say and puts a "No idea!" at the end. If the policeman asks, "Where is the illegal whiskey distillery?", Tony says, "Where is the illegal whiskey distillery? No idea!"

Give defiant answers

Task:

  1. Create a new class, and ask for input from the command line.

  2. Depending on the input, distinguish three cases:

    • If the input ends with a ?, then output to the screen whatever is coming from the input, but append " No idea!" at the end.

    • If no question is asked by the police — the input does not end with ? — Tony the Defiant keeps his mouth shut completely.

    • If the input is "No idea?", and regardless of the case, Tony defiantly replies "Aye!".

1.1.5. Test strings for palindrome property ⭐

A palindrome is a word that reads the same from the front as from the back, such as "Otto" or even "121".

The fact that such words and even sentences exist at all amuses Captain CiaoCiao since he can entertain the audience with it. However, he is always presented with strings that are not palindromes. Therefore, all words must be tested beforehand.

PalindromeTester

Task:

  • Write a Java program that examines whether a string is a palindrome.

    • Create a new class PalindromeTester.

    • Implement a static method boolean isPalindrome(String s).

    • Enhance the program with a class method boolean isPalindromeIgnoringCase(String s), so that the test becomes case-insensitive.

    • Now, all characters that are not letters or digits should also be ignored. Character.isLetterOrDigit(char) helps to detect this. This can be used to check sentences like A man a plan a canal Panama or Pepe in Tahiti never has pep or Be mean - always be mean! Let’s call the method isPalindromeIgnoringNonLettersAndDigits(String).

1.1.6. Check if Captain CiaoCiao is in the middle ⭐

Captain CiaoCiao is the center of the world, so he expects to be in the center in all texts as well.

Check if Captain CiaoCiao is in the middle

Task:

  • Write a method boolean isCiaoCiaoInMiddle(String) that returns true if the string "CiaoCiao" is in the middle.

Examples:

  • isCiaoCiaoInMiddle("CiaoCiao")true.

  • isCiaoCiaoInMiddle("!CiaoCiao!")true

  • isCiaoCiaoInMiddle("SupaCiaoCiaoCute")true

  • isCiaoCiaoInMiddle("x!_CiaoCiaoabc")true

  • isCiaoCiaoInMiddle("\tCiaoCiao ")true

  • isCiaoCiaoInMiddle("BambooCiaoCiaoBlop")false

  • isCiaoCiaoInMiddle("Bernie und Ert")false

1.1.7. Find the shortest name in the array ⭐

Bonny Brain uses only the shortest call name for a person.

ShortName

Task:

  • Write a method String shortestName(String... names) that returns the shortest partial string of all full names. The string can also contain exactly one space if the name is composed of parts. In other words, there are strings with one name or strings with two names.

  • If there are no names, the answer is an empty string.

  • The vararg array must not be null, and no string in the array must be null.

Example:

  • shortestName("Albert Tross", "Blowfish", "Nick Olaus", "Jo Ker")"Jo"

1.1.8. Count string occurrences ⭐

Captain CiaoCiao eliminated the developer Dev David in a careless action. He was in the process of writing a method; the Javadoc is ready, but the implementation is missing.

/**
 * Counts how many times the substring appears in the larger string.
 *
 * A {@code null} or empty ("") String input returns {@code 0}.
 *
 * <pre>
 * StringUtils.countMatches(null, *)       = 0
 * StringUtils.countMatches("", *)         = 0
 * StringUtils.countMatches("abba", null)  = 0
 * StringUtils.countMatches("abba", "")    = 0
 * StringUtils.countMatches("abba", "a")   = 2
 * StringUtils.countMatches("aaaa", "aa")  = 2
 * StringUtils.countMatches("abba", "ab")  = 1
 * StringUtils.countMatches("abba", "xxx") = 0
 * </pre>
 *
 * @param string  the String to check maybe null
 * @param other   the substring to count maybe null
 * @return the number of occurrences, 0 if either String is {@code null}
 */
public static int countMatches( String string, String other ) { return null; }

Note: The * in the Javadoc symbolizes an arbitrary argument.

Task:

  • Implement the method.

1.1.9. Determine the larger crew size ⭐

Bonny Brain is studying old logbooks that show the strength of her crew and captured ships:

|-|||
|-||
|||-|||
|||||-||

Each crew member is symbolized by a dash, a minus sign separates the crew size. On the left is the number of people on their ship, on the right is the number on the raided ship.

Determine the larger crew size

Task:

  • The dashes are hard to read for Bonny Brain. Write a program that makes the coding clear:

    |-|| => Raided ship had a larger crew, difference 2
    |-|| => Raided ship had a larger crew, difference 1
    ||-|| => Ships had the same crew size
    |||||-|| => Pirate ship had a larger crew, difference 3

1.1.10. Build diamonds ⭐⭐

Captain CiaoCiao likes diamonds, the bigger, the better.

Build diamonds

Task:

  • Write a program that generates the following output:

       A
      ABA
     ABCBA
    ABCDCBA
     ABCBA
      ABA
       A

    Using a prompt on the console, it should be possible to specify the maximum width of the diamond. In our example, this is 7 — the length of the string ABCDCBA. The only input for the width that can be achieved with strings of ascending and descending uppercase letters should be accepted, i.e., at most the length of ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVU…​BA.

1.1.11. Check for a good password ⭐

All the dirty secrets are encrypted by Captain CiaoCiao, but too often his password was too simple and was guessed. He has learned that a secure password is important for his business, but he can’t quite remember the rules: a good password has a certain length, contains special characters, etc.

Check for a good password

Task:

  1. Create a new class PasswordTester.

  2. Write a method isGoodPassword(String) that tests some criteria. The method should return false if the password is weak, and true if the password has a proper syntax. If a test fails, a message should appear via System.err and no further checks should take place.

1.1.12. Bake Peanut Butter Cookies ⭐⭐

Just before the holiday, the crew gathers around Captain CiaoCiao to bake peanut butter cookies. The amateur bakers bring either peanut butter, sugar, or eggs. When they arrive, they sit down at a table one by one and want to start baking.

Given is a list of all the ingredients that the amateur bakers have brought. The list is represented as a string, where P stands for peanut butter, S for sugar, and E for egg. The string could be: PSESEPESP or also PPPEEESSS.

As long as there are three amateur bakers sitting next to each other and have peanut butter, sugar, and eggs, baking can be carried out regardless of the order of the ingredients.

Bake Peanut Butter Cookies

Task:

  • Determine how many times peanut butter cookies can be baked, that is, the three ingredients come together directly next to each other in any order.

  • Amateur bakers who have failed to listen carefully may bring entirely different ingredients, such as rum, licorice, or marinated eel, which cannot be used to bake peanut butter cookies.

Examples:

  • "PSESEPESP" → 3

  • "PPPEEESSS" → 0

  • "SEPEPLSEE" → 1

1.1.13. Calculate sum of digits ⭐

As Bonny Brain is often responsible for issuing payments and is concerned that someone may alter the amounts, she employs a trick whereby she sends the cross sum along with the amount through a separate channel.

The cross sum of a number is formed by adding each digit of the number. For example, if the number is 10938, the cross sum is 1 + 0 + 9 + 3 + 8 = 21.

Calculate sum of digits

Task:

  1. Create a new class SumOfTheDigits.

  2. Write a class method int digitSum(long value) that calculates the cross sum of a number.

  3. Add an overloaded class method int digitSum(String value) that takes the digits in a string.

Which method is easier to implement? Which method should call the other as a subroutine?

1.1.14. Decolumnize texts ⭐⭐

Captain CiaoCiao is scanning old logbooks, but they were originally in columns. After OCR text recognition, the columns are preserved.

Since this is hard to read, the two columns should be recognized and translated into a regular continuous text without columns.

Decolumnize texts

Task:

  • Write a method decolumnize(String) that searches for the column and returns a text with one column from a text with two columns.

Example:

I’m dishonest, and a to watch out for,
dishonest man you    because you can
can always trust to  never predict when
be dishonest.        they’re going to do
Honestly, it’s the   something incredibly
honest ones you want stupid.

I’m dishonest, and a
dishonest man you
can always trust to
be dishonest.
Honestly, it’s the
honest ones you want
to watch out for,
because you can
never predict when
they’re going to do
something incredibly
stupid.

Each column is separated by at least one space. Note that the right and left columns can have incomplete blank lines!

1.1.15. Draw a meadow with favorite flowers ⭐⭐

Captain CiaoCiao wants to beautify his ship and decorate it with flowers. He finds a graphic by Joan G. Stark to use as a template and thinks about how to tell the painters and decorators what patterns he wants in the cabin.

                _
              _(_)_                          wWWWw   _
  @@@@       (_)@(_)   vVVVv     _     @@@@  (___) _(_)_
 @@()@@ wWWWw  (_)\    (___)   _(_)_  @@()@@   Y  (_)@(_)
  @@@@  (___)     `|/    Y    (_)@(_)  @@@@   \|/   (_)\
   /      Y       \|    \|/    /(_)    \|      |/      |
\ |     \ |/       | / \ | /  \|/       |/    \|      \|/
\\|//   \\|//   \\\|//\\\|/// \|///  \\\|//  \\|//  \\\|//
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Draw a meadow with favorite flowers

Task:

  1. Copy the flowers into a string. Tip: Create a string like String flower = "";, put the flower string on the clipboard, and paste it between the quotes in the IDE; IntelliJ and Eclipse will then independently encode the special characters like \ and \n. Java text blocks are also a viable option for this multiline string.

  2. There are 8 kinds of flowers, and we can number them from 1 to 8. We encode the order as a string, for example "12345678". It should now be possible to change the order and have flowers appear more than once, for example by encoding "8383765432". If an identifier is wrong, the first flower will always appear automatically for it.

Examples:

  • "838" leads to

       _    _(_)_      _
     _(_)_ (_)@(_)   _(_)_
    (_)@(_)  (_)\   (_)@(_)
      (_)\      `|/   (_)\
         |      \|       |
        \|/      | /    \|/
      \\\|/   \\\|//  \\\|/
    ^^^^^^^^^^^^^^^^^^^^^^^
  • "ABC9" leads to

      @@@@   @@@@   @@@@   @@@@
     @@()@@ @@()@@ @@()@@ @@()@@
      @@@@   @@@@   @@@@   @@@@
       /      /      /      /
    \ |    \ |    \ |    \ |
    \\|//  \\|//  \\|//  \\|//
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Hold the locations for the transition between the flowers in an array.

1.1.16. Detect repetitions ⭐⭐⭐

Captain CiaoCiao flips through a book and finds patterns of the sort 🌼🌻🌼🌻🌸🌼🌻🌼🌻🌸🌼🌻🌼🌻🌸. How reassuring for him. He wants to make stamps for printing, so he can print such sequences of patterns himself. Of course, the cost should be reduced, but the stamp itself should not contain any repetitions of symbols. For a given pattern sequence, a program needs to be developed that determines the minimum sequence of symbols that need to be on the stamp.

Task:

  • Write a method String repeatingStrings(String) that returns the repeating string in case of repetition, otherwise null if no substring repeats.

Examples:

  • repeatingStrings("🌼🌼🌼") returns "🌼".

  • repeatingStrings("🌼🌻""🌼🌻""🌼🌻") returns "🌼🌻".

  • repeatingStrings("Ciao"+"Ciao") returns "Ciao".

  • repeatingStrings("Captain CiaoCiaoCaptain CiaoCiao") returns "Captain CiaoCiao".

  • repeatingStrings("🌕🌔🌓🌑") returns null.

  • repeatingStrings("CaptainCiaoCiaoCaptain") return null

  • repeatingStrings("🌼") returns null

  • repeatingStrings("") return null

  • repeatingStrings(null) return null

Note: repeatingStrings(…​) should return the shortest repeating string.

1.1.17. Constrain line boundaries and wrap lines ⭐⭐

Bonny Brain is switching to carrier pigeons for communication, and there isn’t too much space on the paper. Now all texts must be reduced in width.

Constrain line boundaries wrap lines

Task:

  • Write a class WordWrap with a static method String wrap(String string, int width) that splits a string without line breaks into small substrings of maximum width width and returns them separated by \n. Inside words — and punctuation marks belong to the word — should not be forcibly wrapped!

Example:

  • The call to

    String s = "Live now; make now always the most precious time. "
             + "Now will never come again.";
    System.out.println( wrap( s, 10 ) );

    returns the following output with a maximum line length of 30:

    Live now; make now always the
    most precious time. Now will
    never come again.

1.1.18. Test if the fruit is wrapped in chocolate ⭐⭐

Captain CiaoCiao likes fruit skewers covered in chocolate. Sara gets the job of frosting the fruit, making different layers of dark and white chocolate.

Bambi checks to make sure the layers are correct. If she sees dhFhd, she knows that the fruit F got first a layer of white chocolate, then a layer of dark chocolate. At dhhd the fruit is missing, and this does not match Captain CiaoCiao’s expectation. At ddhFh the layer is broken, which is also not right. And at F the chocolate is completely missing, what a disappointment!

Test if the fruit is wrapped in chocolate

Task:

  • Write a recursive method checkChocolate(String) that checks if the string is symmetric, that is, on the left and the right is the same type of chocolate, and in the middle is the fruit F.

Optional: Extend the program in case the string is two-dimensional, e.g.

String fruit =
  "ddddd\n" +
  "dhhhd\n" +
  "dhFhd\n" +
  "dhhhd\n" +
  "ddddd" ;

1.1.19. From top to bottom, from left to right ⭐⭐⭐

In a cave Bonny Brain discovers a text, however, the text does not run from left to right, but is written from top to bottom.

s u
ey!
ao

Written vertically, this is the string sea you! — and it’s much easier to read!

From top to bottom from left to right

Task:

  • Write a method printVerticalToHorizontalWriting(String) that returns a string to its horizontal position and prints it. The argument is a string in which line feeds separate the lines.

Example:

  • Let’s stick with the string from above:

    String s = "s u\ney!\nao ";
    printVerticalToHorizontalWriting( s );

    The output on the screen will be sea you!.

Three important assumptions should hold:

  1. Lines are separated only with `\n

  2. Each line is the same length; for example, the last line has space so that all lines are 3 characters (in this example) long (not counting line breaks).

  3. There is no \n at the end of the string.

1.2. Dynamic strings with StringBuilder

While String objects are immutable, objects of java.lang.StringBuilder can be modified. The same is true for StringBuffer, but this class is API-like and not relevant for the exercises.

1.2.1. Fill strings ⭐

Captain CiaoCiao loves freedom, and spacing is essential to him. Even with texts, he thinks, the letters could have a little more spacing.

Fill strings

Task:

  • Write a method mix(String, String) that spreads a string and puts fill characters between all characters.

  • The parameters may be null.

Examples:

  • mix( "We’re out of rum!", "-" )"W-e-'-r-e- -o-u-t- -o-f- -r-u-m-!"

  • mix( "Blimey", "👻" )"B👻l👻i👻m👻e👻y"

  • mix( "HI", "♥" )"H♥I"

  • mix( "♥", "!!" )"♥"

  • mix( "", "👻" )""

1.2.2. Practicing the alphabet with a parrot ⭐

Captain CiaoCiao is teaching his parrot the alphabet. To save himself time and effort, he uses a program that generates the alphabet for him.

Given is the following method:

static String abcz() {
  String result;
  result = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  return result;
}

The method returns a string with all characters in the alphabet from 'A' to 'Z'. So Captain CiaoCiao can copy the string to an input field at https://ttsreader.com/de/ and let it read aloud. However, there must then be spaces between the letters to make the sound better.

The method is performant in its task, but not very flexible, for example, when it comes to generating only certain ranges, such as from '0' to '9'. Because the parrot can already do ABC very well, but from G to Z it gets tough.

Practicing the alphabet with a parrot

Task:

  • Change the method abcz() so that the String is dynamically generated via a loop.

  • Add a method String abcz(char start, char end) that generates a string with all symbols between the start character start and the end character end; the end character is included and belongs to the string.

  • Write a method String abcz(char start, int length) which returns length characters starting from start. Can one of the methods be mapped to the other?

  • Consider how to handle incorrect parameters, such as when the end index is before the start index.

The primitive data type char is nothing more than a numeric positive data type that can be converted to the data type int. Consequently, we can calculate with a char, and if we take the letter 'A' and add 1 to it, we come out with 'B'.

1.2.3. Convert number to textual unary encoding ⭐

Captain CiaoCiao is worried about the safety of his crew, and therefore he wants to disguise the amount of loot from the raids. Only two symbols are supposed to be used for this purpose.

The unary encoding represents a natural number n as follows:

nunary encoding

0

0

1

10

2

110

3

1110

4

11110

A positive integer n is represented by n ones followed by a zero. By the way, a code of this kind is called prefix-free because no word is the prefix of another word. In the encoding, we could also swap 0s and 1s without any problem, and the prefix characteristic does not change.

Unary encoding results in codes of different lengths.

Convert number to textual unary encoding

Task:

  • Write a method String encode(int... values) that creates a string from a vararg array with integers, in which all unary encoded values from the array are concatenated.

  • Add a method int[] decode(String value) that turns a unary encoded string back into an int array.

Example:

  • encode( 0, 1, 2, 3, 0, 1 )"0101101110010"

  • encode( 0, 0, 0 )"0000"

  • encode()""

  • Arrays.toString( decode("0101101110010") )[0, 1, 2, 3, 0, 1]

1.2.4. Lose weight by moving digits ⭐

Bonny Brain has noticed that it’s great to cheat on freight charges. The people in charge in the office often forget the exact weight, but they can remember the occurring digits perfectly, and it is not noticed if at most two digits are swapped. Bonny Brain uses this to its advantage by putting the smallest digit in the number forward to achieve a smaller weight, but 0 must be ignored, otherwise the length of the number changes, and this is noticeable.

cheated Weight

Task:

  • Write a method int cheatedWeight(int weight) that does exactly this transformation.

Examples:

  • cheatedWeight(0)0

  • cheatedWeight(1234)1234

  • cheatedWeight(4321)1324

  • cheatedWeight(100)100

  • cheatedWeight(987654321)187654329

1.2.5. Remove vowels ⭐

Captain CiaoCiao is spitting out her memoir faster than a cannonball, and poor Kiko Kokopu can’t keep up with the note-taking. What if we just leave out all the boring old vowels? A wise linguist once claimed that even without the A, E, I, O, U’s, a text can still be understood. Common vowel letters are: A, E, I, O, U. Is it true what the scientists say and can we understand this captain’s salty tale without any vowels?

Task:

  1. Create a new class RemoveVowel.

  2. Write a class method String removeVowels(String string) that removes the vowel letters from a passed String.

  3. Solve the task with at least two different variants.

Examples:

  • "Hello Javanese""Hll Jvnsn"

  • "BE NICE""B NC"

1.2.6. Don’t shoot the Messenger ⭐

Bonny Brain is cooking up a devious plan to send a secret message without it falling into the wrong hands. She’s so paranoid that the messenger might get ambushed and spill the beans! So, she’s come up with a cunning scheme—​she’s sending multiple messengers, each with a part of the message. The scheme is like this:

  • A text is broken down into letters.

  • Messenger 1 gets the 1st letter

  • Messenger 2 gets the 2nd letter

  • messenger 1 gets the 3rd letter

  • messenger 2 gets the 4th letter

  • etc.

The recipient of the message must now wait for the two messengers, know the original order, and reassemble the message.

Dont shoot the Messenger

Task:

  • Write a method String joinSplitMessages(String...) that takes any number of the split messages and returns the assembled string.

  • If message parts are missing, this should not cause an error.

Examples:

  • joinSplitMessages("Hoy", "ok")"Hooky"

  • joinSplitMessages("Hooky")"Hooky"

  • joinSplitMessages("Hk", "oy", "o")"Hooky"

  • joinSplitMessages( "H", "", "ooky" )"Hooky"

1.2.7. Compress repeated spaces ⭐⭐

Bubbles listen in on a conversation for Captain CiaoCiao and then transcribes it. But because she’s so busy munching on peanuts that she accidentally jams the space bar on her transcription machine! Before she knows it, spaces start doubling up. Poor Bubbles, she can’t give the captain a garbled message like this.

Task:

  • Write a static method StringBuilder compressSpace(StringBuilder string) that merges more than two spaces in the passed string into one space.

  • The passed string should be returned with return string;, the change should be done directly at StringBuilder.

Example:

  • "Will ​ ​ you shut up, ​ man! ​ ​ This is the way!""Will you shut up, man! This is the way!"

1.2.8. Insert and remove crackles and pops ⭐

Messages over the radio often have crackling, which is distracting Captain CiaoCiao.

Insert remove crackles pops

Task:

  • Write two methods:

    • String crackle(String) should insert "♬CRACK♪" at arbitrary intervals and return the crackle string.

    • String decrackle(String) shall remove the crackle again.

1.2.9. Split CamelCase strings ⭐

To save volume when transmitting text by telegraph, Funker Frogfish uses a trick: He capitalizes the next character after space and then deletes the space. ciao ciao becomes ciaoCiao. If the next character is already an uppercase letter, only space is removed, thus Ciao Ciao becomes CiaoCiao. Since the uppercase letters within the series of lowercase letters look like humps, the spelling was named CamelCase.

Captain CiaoCiao receives the strings, but it is hard to read such a text.

Task:

  • Write a new method String camelCaseSplitter(String) that separates all CamelCase segments again.

Examples:

  • camelCaseSplitter("List")"List"

  • camelCaseSplitter("CiaoCiao")"Ciao Ciao"

  • camelCaseSplitter("numberOfElements")"number Of Elements"

  • camelCaseSplitter("CiaoCiaoCAPTAIN")"Ciao Ciao CAPTAIN"

If words are completely in uppercase, as in the last case, only the change between lowercase and uppercase applies.

1.2.10. Underline words ⭐⭐

Sporadically, Bonny Brain has to call the crew’s attention to rules. She does this by writing a message and underlining the important words. Bonny Brain has underlined the word "treasure" in the following message:

There is more treasure in books than in all the pirates' loot on Treasure Island
              -------- --------

Task:

  1. Create a new class PrintUnderline.

  2. Write a new static method printUnderline(String string, String search) that underlines each string search in string as shown in the example above. Keep in mind that search can occur more than once in the string or not at all.

  3. The case of the search string should not matter, as also shown in the example.

1.2.11. Implement Caesar encryption ⭐⭐⭐

Captain CiaoCiao discovered the ancient art of encryption that is supposed to have already been used by Gaius Julius Caesar. The captain is so impressed by the Roman general that he’s decided to use the same encryption method for his own texts. But can he really outsmart his enemies with this ancient code?

The Caesar encryption involves shifting each character three positions in the alphabet. For instance, A is replaced by D, B by E, and so on. Once the end of the alphabet is reached, the sequence starts over, resulting in X becoming A, Y becoming B, and Z becoming C.

Caesar encryption

Task:

  1. Create a new class Caesar.

  2. Implement a method String caesar(String s, int rotation) that does the encryption. rotation is the shift, which could be arbitrary, not only 3 as from the input example.

  3. Write a method String decaesar(String s, int rotation) which takes back the encryption.

  4. Caesar encryption falls into the class of decryption ciphers. Is it Captain CiaoCiao to be recommended?

Example:

  • caesar( "abxyz. ABXYZ!", 13 )"noklm. NOKLM!"

  • decaesar( caesar( "abxyz. ABXYZ!", 13 ), 13 ) )"abxyz. ABXYZ!"