PRACTICE
STRINGS



Steps

  1. Copy-paste the text below into a String variable called charlieB.

Only once a year, on his birthday, did Charlie Bucket ever get to taste a bit of chocolate. The whole family saved up their money for that special occasion, and when the great day arrived, Charlie was always presented with one small chocolate bar to eat all by himself.

  1. Write a line of code to print out…
  1. The length of charlieB.
  2. The first character of charlieB.
  3. The last character of charlieB.
  4. The character at index 89 of charlieB.
  5. The substring of charlieB that includes the characters at index 81 to 89. Confirm it includes index 89 by referencing what you printed in 2d.
  6. The substring “Charlie Bucket” from charlieB.
  7. The substring “all by himself” from charlieB.
    Hint: There are a lot of indices in charlieB. Maybe you should use a method to help you find where this starts. You surely wouldn’t count that all out, right?
  8. A boolean value to confirm that the substring “birthday” is in charlieB.
    Hint: Remember that I didn’t teach you all the possible String methods! There’s a method that does this very easily for you. You just need to find it.
  1. Print out a boolean value that reflects if “Chocolate” is in charlieB. Not “chocolate”. “Chocolate”.
  2. On a new line in your program, include
    charlieB = charlieB.toUpperCase();. Notice that you are reassigning charlieB to be something new! Print out charlieB to see how it’s changed.
  3. Print out a boolean value to check if “CHOCOLATE” is in charlieB. Not “chocolate” or “Chocolate”. You’re checking if “CHOCOLATE” is in charlieB.
  4. charlieB is looking a little intimidating now. On a new line, write charlieB = charlieB.toLowerCase();. Print out charlieB.
  5. Print out a boolean value to check if “chocolate” is in charlieB. In your head, ponder why it may be useful to use either toUpperCase() or toLowerCase() when checking if a certain substring is in a String.
  6. On a new line in your program, write System.out.println(charlieB.indexOf("chocolate")); (which we know is in charlieB) Why was that number printed?
    Hint: If you aren’t sure, refer to question
    2e).



  7. Reassign charlieB to remove all characters from 81 to 89 inclusive.
  8. Concatenate the new line character \n to the end of charlieB.
  9. Below is the next part of the story. Concatenate it to the end of charlieB, then print out charlieB.

And each time he received it, on those marvellous birthday mornings, he would place it carefully in a small wooden box that he owned, and treasure it as though it were a bar of solid gold; and for the next few days, he would allow himself only to look at it, but never to touch it.

  1. Write charlieB = charlieB.replace("birthday", "b-day"); Print out charlieB to see what’s changed.