String manipulation

A very common activity in programming is to take a string and manipulate it. Common operations you will want to do include:

  • Determine the length of a string
  • Join two strings together
  • Extract part of a string into another string
  • Find the position of a single character in a string
  • Compare one string with another
  • Convert a string from upper case to lower case or vice versa
  • Trim a string to remove certain characters from it

Activity 1

To start your exploration of strings it might be useful to use a spreadsheet which can allow you to easily try string manipulations.

Type a sentence into a cell. Then use text functions such as LEN, LEFT, RIGHT, MID, UPPER, FIND and TRIM to manipulate that text. Most spreadsheet software gives you hints on how to use these functions as you type them in so pay attention as you type.

Activity 2

Have a look at some of the operations available to you in Java by visiting the documentation here and finding the String class. Which methods in the Strong class are equivalent to the above spreadsheet functions? How can you compare the contents of two strings? Does == work as it does with other data types?

Try out some of the String class methods using BlueJ’s codepad.

Activity 3

  1. Write some code to take in a sentence at the keyboard and then output it again, converted all to upper case.
  2. Write some code to take the spaces off the beginning or end of an input sentence.
  3. Write some code that prints the nth character from a given string (both n, and the string should be input by the user).
  4. Write some code that takes in a sentence and counts the number of words in it.
  5. Write some code that takes in a sentence and counts the number of words and the number of letters in a sentence.

Knowledge check

Java provides a huge number of prewritten methods that allow strings to be manipulated.

Assuming string1 contains “string@manipulation.com”

  • What would string1.length() return?
  • What would string1.substring(0,6) return?
  • What method gives you one character at a particular position in string1?
  • What method gives you the position of particular character within string1?