Strings Reading for this Lecture, L&L, 3.2
Strings String is basically just a collection of characters. Thus, the string “Martyn” could be thought of as a 6-element array ('M', 'a', 'r', 't', 'y', 'n'). The String class allows us to manipulate these data items.
Strings in java String is a class in Java Strings are constant (values cannot be changed after they are created) Set of characters "Lisa Simpson" is a string. "A" is a string, 'A' is a character. Note the difference here. Character literals are delimited by single quotes and String literals are delimited by double quotes.
Methods on Strings The String class provides methods to – Return the character at a specific index (charAt) – Return the index of a specific character (indexOf) – Compare two strings (compareTo) – Concatenate two strings (concat) – Check the length of a string (length) – Extract a sub-string (substring) – Replace all instances of a character with another character (replace)
How long is a String Use length() to find out how long a string is String test; test = new String("The quick, brown"); System.out.println("Length of test is: “ + test.length()); Works on anonymous strings too: System.out.println("Lisa Simpson is: “ + "Lisa Simpson".length() + " characters long.");
Finding characters in String at specific index Strings are character sequences Grab individual characters with charAt() public char charAt(int index) A quick example: String test = “Hello” for (int nextChar = 0;nextChar < test.length(); nextChar++) { System.out.println(test.charAt(nextChar)); } HelloHello Output H is the character at index 0, e at index 1 and so on
Finding index of particular character We can find index of characters using following two methods indexOf(int) lastIndexOf(int) Examples "abcdefabc".indexOf(‘b’) is 1 "abcdefabc".lastIndexOf(‘b’) is 7
Substrings A substring is a string within a string Substring method – public String substring (int beginIndex, int endIndex) Includes character at beginIndex, but not the character at endIndex. “Hello World".substring(3,8) is “lo Wo”.
Replace character with another character Replace one character with another in a new string replace (char oldChar, char newChar) Example: String name = “Hello World"; String new_name = name.replace(‘e', ‘a'); // new_name will be “Hallo World”
Case Conversion Make a copy of a string, all in one case Handy for enforcing consistency: always switch strings to upper case or lower case public String toLowerCase() public String toUpperCase()