|
|
1. STRINGS |
A special kind of array is the string which is essentially an array whose elements are of the type char. Thus the string: "FRANS" (remember that strings are indicated by double quotes) can be thought of as the character array: {'F', 'R', 'A', 'N', 'S'} (Remember that characters are indicated by single quotes.) Alternatively we can describe a string in terms of a sequence of Unicodes (in hexadecimal notation): "\u0046\u0052\u0041\u004E\u0053" The need for "string" data items in computer programming is so frequent that many programming languages provided a predefined string type. Java, while remaining with the concept of a string being an array of characters, does not do this; instead it provides a predefined class called String. We use this in the same manner that we might use any other predefined class. For example we might declare an instance of the String class as follows: String name = new String(); However, in Java (unlike most other instances) instances of the class String are always constants, i.e. their value is fixed on construction. Thus to assign a value to the instance name we must do this when it is created. If we study the String class in the Java API we will notice that there are currently (August 2003) eleven different String class constructors, one defualt constructor and ten others with different argument types and arrity (the numbers of arguments) including a constructor that takes as its argument an array of characters: String name = new String(char[] val); |
Now consider the code given in Table 1. Here we have created a 5 element charcater array, called data. We then used this array as the argument for the String constructor to create a (constant) data item called name which has the value FRANS which is itself a character array. Because instances of the class String are so common Java provides a short hand to achieve the above as shown in Table 2.
Table 1: String example code 1
Table 2: String example code 2 |
2. OPERATIONS ON STRINGS |
The class String provides many methods that may be used to perform operations on strings. A selection is presented in Table 3.
Method prototype | Description |
---|---|
char charAt(int index) | Returns the character at the specified index. |
int compareTo(String anotherString) | Compares two strings lexicographically. |
String concat(String str) | Concatenates the specified string to the end of the this string. |
str1 + str2 | Concatenation operator, achieves same as concat method. |
boolean endsWith(String str) | Tests if the this string ends with the specified suffix (str). |
boolean equals(String str) | Compares the this string to the specified object. |
boolean equalsIgnoreCase(String str) | Compares the this String to str, ignoring case considerations. |
int indexOf(char ch) | Returns the index within the this string of the first occurrence of the specified character. |
int lastIndexOf(char ch) | Returns the index within the this string of the last occurrence of the specified character. |
int length() | Returns the length of the this string. |
String replace(char oldChar, char newChar) | Returns a new string resulting from replacing all occurrences of oldChar in the this string with newChar. |
boolean startsWith(String str) | Tests if the this string starts with the specified suffix (str). |
String substring(int beginIndex, int endIndex) | Returns a new string that is a substring of the this string. |
String toLowerCase() | Converts all of the characters in the this String to lower case. |
String toUpperCase() | Converts all of the characters in the this String to upper case. |
trim() | Removes white space from both ends of the this String. |
Table 3: Selection of methods in the String class
There are many more and also variations on the methods presented in Table 3. The Java code presented in Table 4 illustrates how many of the operators and methods listed above may be used. The output from this code is given in Table 5.
// STRING EXAMPLES // Frans Coenen // Monday 24 February 1999 // The University of Liverpool, UK class StringEx { // --------------- METHODS ------------------ /* MAIN METHOD: */ public static void main(String[] args) { String name1 = "\u0046\u0052\u0041\u004E\u0053"; String name2 = "COENEN"; String name3 = "FRANS COENEN"; // Sequence of method calls illustrating string manipulation lengthOfString(name1); charcaterAtIndexN(name1); compareStrings(name1,name2); concatination1(name1,name2); concatination1(name1,name2); occurancesOfN(name3); subString(name3); replaceCharacter(name3); caseConversion(name1); } /* LENGTH Of STRING: Example method to illustrate use of length method */ public static void lengthOfString(String name) { System.out.println("LENGTH OF STRING"); System.out.println("Length of string" + name + " is " + name.length() + "\n"); } /* CHARACTER AT INDEX N: Example method illustrating use of charAt method. */ public static void charcaterAtIndexN(String name) { System.out.println("CHARACTER AT INDEX N"); for (int index=0;index < name.length();index++) System.out.print(name.charAt(index) + " "); System.out.println("\n"); } /* COMPARE STRINGS: Example method illustrating use of compareTo and equals methods */ public static void compareStrings(String name1, String name2) { System.out.println("COMPARE STRINGS"); // The compareTo method System.out.print("Compare " + name1 + " and " + name2 + " = " + name1.compareTo(name2) + "\n"); System.out.print("Compare " + name2 + " and " + name1 + " = " + name2.compareTo(name1) + "\n"); System.out.print("Compare " + name2 + " and " + name2 + " = " + name2.compareTo(name2) + "\n"); System.out.print(name1 + " and " + name2 + " are "); // Using the compareTo method within an if-else statement if (name1.compareTo(name2)==0) System.out.println("the same"); else System.out.println("not the same"); // The equals method System.out.print("Equals " + name2 + " and " + name1 + " = " + name2.equals(name1) + "\n"); System.out.println("Equals " + name2 + " and " + name2 + " = " + name2.equals(name2) + "\n"); } /* CONCATENATION 1: Example method illustring use of concat method */ public static void concatination1(String name1, String name2) { System.out.println("CONCATENATION 1"); name1 = name1.concat(" "); name1 = name1.concat(name2); System.out.println("name1 = " + name1 + "\n"); } /* CONCATENATION 2: Example method illustring use of + (concatination) operator. Same effect as above. */ public static void concatination2(String name1, String name2) { System.out.println("CONCATENATION 2"); name1 = name1 + " " + name2; System.out.println("name1 = " + name1 + "\n"); } /* OCCURANCES OF N: Example method illustrating use of indexOf and lastIndexOf method */ public static void occurancesOfN(String name) { System.out.println("OCCURANCES OF N"); // Find first and last occurances of N in argumnet System.out.println("First occurance of 'N' in " + name + " is at index " + name.indexOf('N')); System.out.println("Last occurance of 'N' in " + name + " is at index " + name.lastIndexOf('N')); // What happens if we are looking for the index of something // that does not exist in the given string? System.out.println("First occurance of 'B' in " + name + " is at index " + name.indexOf('B')); // Find all occurances of N in argument int index=0; while (name.indexOf('N',index) != -1) { index = name.indexOf('N',index); System.out.println("Occurance of 'N' in " + name + " is at " + index); index++; } System.out.println(); } /* SUBSTRINGS: Example method illustrating use of substring method */ public static void subString(String name1) { System.out.println("SUBSTRINGS"); // Substring from index 4 omwards System.out.println("Substring from index 4 onwards = " + name1.substring(4)); // Substring comprising all of input String name2 = name1.substring(0,name1.length()); System.out.println("Entire copy of " + name1 + " = " + name2); // Substring from N to M name2 = name1.substring(0,2); System.out.println("Substring from index 0 to 2 = " + name2); // Substring made up of name2 from above (first three charcaters // of name1) plus substring from the first occurance of a space // (' ') in name 1 to three charcaters beyond it. name2 = name2.concat(name1.substring(name1.indexOf(' '), name1.indexOf(' ')+3)); System.out.println("name2 = " + name2 + "\n"); } /* REPLACE CHARACTER: Example method illustrating use of replace method */ public static void replaceCharacter(String name1) { System.out.println("REPLACE CHARACTER"); // Replace R and O with . name = name.replace('R','.'); name = name.replace('O','.'); System.out.println("name = " + name + "\n"); } /* CASE CONVERSION: Example method illustrating use of toLowercase and toUpperCase methods */ public static void caseConversion(String name1) { System.out.println("CASE CONVERSION"); // Upper to lower case conversion name1 = name1.toLowerCase(); System.out.println("name1 = " + name1); // Lower to upper case conversion name1 = name1.toUpperCase(); System.out.println("name1 = " + name1); // Substrings and case conversion String name2 = name1.substring(0,1); String name3 = name1.substring(1,5); name2 = name2.concat(name3.toLowerCase()); System.out.println("name2 = " + name2 + "\n"); } } |
Table 4: Usage of a selection of string operations.
Notes:
|
Table 5: Output from example code given in Table 4. |
Created and maintained by Frans Coenen. Last updated 10 February 2015