Tonga Institute of Higher Education String Manipulation Tonga Institute of Higher Education
Introduction We know how to combine strings together and why this is useful Why is it useful to break strings apart? Extraction of data Example: My birthday is “07-07-76”. How can we determine the year from this string? How do we break strings apart?
String.charAt Method - 1 A char datatype is different from a String datatype A char is only 1 character (letter) ‘a’ ‘5’ A String contains many characters “Hello” “Sione” You can get the char for each location in a string using the charAt method
String.charAt Method - 2 A String is like an array of characters 1 2 3 4 Index A String is like an array of characters Each cell of this array contains 1 character To get a character located at an index, we can use the charAt method Prints H
String.subString Method - 1 l o 1 2 3 4 Index Use the subString method to get a smaller string from a larger string Example: To get “Sione” from “Sione Tupou”
String.subString Method - 2 l o 1 2 3 4 Index 1 2 The first method has only 1 parameter It returns everything from that index to the end of the string Prints “lo”
String.subString Method - 3 l o 1 2 3 4 Index 1 2 The second method has only 2 parameter It returns everything from the first index up to the second index Prints “ll”
String.indexOf Method - 1 l o 1 2 3 4 Index Use the indexOf method to get the index number of a char or a string Example: To find that the index of the first ‘l’ char is 2 -1 is returned if the char or string doesn’t exist 1 2 3 4
String.indexOf Method - 2 l o 1 2 3 4 Index 1 2 3 4 Returns 1 Find index of characters Returns -1
String.indexOf Method - 3 l o 1 2 3 4 Index 1 2 3 4 Returns 2 Find index of Strings Returns 3 Start searching from this index
String.length Method To get the number of characters in a string, use the length method Returns 5
More Methods Available trim – Removes whitespace before and after string toUpperCase – Changes all characters to upper case toLowerCase - Changes all characters to lower case Check the API documentation for a complete list of the methods available