Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 4 Characters & Strings Eng. Mohammed Abdualal October 10, 2015
Character Data Type and Operations The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks. Example: char letter = 'A'; char numchar = '5'; In Java, char values represent Unicode characters. Unicode is a 16-bit character encoding that supports the world's major languages. You can indicate a Unicode character using \uxxxx escape sequence. Each X in the escape sequence is a hexadecimal digit. As example, character A can be represented in other way using Unicode encoding: char letter = '\u0041'; // Character A's Unicode is 0041 The following table representing Unicode values for commonly used characters: Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 \u0030 to \u0039 'A' to 'Z' 65 to 90 \u0041 to \u005a 'a' to 'z' 97 to 122 \u0061 to \u007a Escape Sequences for Special Characters Java uses an escape sequence to represent special characters, which consists of a backslash (\) followed by a character or a combination of digits. For example, \t is an escape sequence for Tab character. The symbols in an escape sequence are interpreted as a whole rather than individually. An escape sequence is considered as a single character. 2
The following table lists escape sequences for special characters in java: Escape Sequence Name Unicode Code \b Backspace \u0008 \t Tab \u0009 \n Linefeed \u000a \f Formfeed \u000c \r Carriage Return \u000d \\ Backslash \u005c \ Double Quote \u0022 \ Single Quote \u0027 Task 1 Write ONE Java Statement to print to following lines to the Console: Welcom to "Java" Lab#4: Strings & Loops Casting between char and Numeric Types A char can be cast into a numeric type, for example, int or byte. When a char is cast into a numeric type, the character s Unicode is cast into the specified numeric type. Example: int i = (int) 'A'; // The Unicode of character A is assigned to i System.out.println(i); // i is 65 Implicit casting can be used if the result of a casting fits into the target variable. For example, since the Unicode of 'A' is 65, which is within the range of int, these implicit castings are fine: int i = 'A'; // i is 65 char c = 65; // c is 'A' 3
Note that all numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. If the other operand is a string, the character is concatenated with the string. For example, the following statements " int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System.out.println("i is " + i); // i is 101 int j = 2 + 'a'; // (int)'a' is 97 System.out.println("j is " + j); // j is 99 System.out.println(j + " is the Unicode for character + (char)j); // 99 is the Unicode for character c System.out.println("Chapter " + '2'); display i is 101 j is 99 99 is the Unicode for character c Chapter 2 Task 2 Try to discover the Unicode code for numbers chars: 0, 1, 2,, 9. Comparting and Testing Characters You can use the same numeric comparison operators for comparing characters. Hence, 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). However, Java provides some static methods in Character class for comparing and converting characters. The following table lists some of those useful methods: Method isdigit(ch) isletter(ch) isletterordigit(ch) islowercase(ch) Description Returns true if the specified character is a digit. Returns true if the specified character is a letter. Returns true if the specified character is a letter or digit Returns true if the specified character is a lowercase letter. 4
isuppercase(ch) tolowercase(ch) touppercase(ch) Returns true if the specified character is an uppercase letter. Returns the lowercase of the specified character. Returns the uppercase of the specified character. Example: Write a program that receives a character, and check if it is a digit or letter. If digit, print its Unicode code. If letter, print its toggle case. Else, print not a digit nor a letter. FindTheUnicodeOfACharacter.java String s = JOptionPane.showInputDialog("Enter a character"); // Get the first character of a line char c = s.charat(0); if (Character.isDigit(c)) { // Character implicitly converted into int System.out.println(c + 0); } else if (Character.isUpperCase(c)) { System.out.println(Character.toLowerCase(c)); } else if (Character.isLowerCase(c)) { System.out.println(Character.toUpperCase(c)); } else { System.out.println("Not a digit nor a letter"); } 5
The String Type A string is a sequence of characters. To represent a string of characters, use the data type called String. A sequence of characters are enclosed in double quotation marks. Example: String str = "Hello World"; String is a predefined class in the Java library. It contains many useful methods manipulating characters. The following table lists the String methods for obtaining string length, for accessing characters in the string, for converting a string to upper or lowercases, and for trimming a string. Method Description length() Returns the number of characters in this string. charat(index) Returns the character at the specified index from this string. touppercase() Returns a new string with all letters in uppercase. tolowercase() Returns a new string with all letters in lowercase. trim() Returns a new string with whitespace characters trimmed on both sides. Getting Characters from a String The str.charat(index) method can be used to retrieve a specific character in a string str, where the index is between 0 and str.length() 1. For example, message.charat(0) returns the character W, as shown in the next figure. Note that the index for the first character in the string is 0. 6
Caution Attempting to access characters in a string str out of bounds is a common programming error. To avoid it, make sure that you do not use an index beyond str.length() 1. Example: Write a Java program to prompt the user to enter a line and output the following: How many characters in the line? The fifth character (if exists) All characters in uppercase All characters in lowercase Manipulating String String str = JOptionPane.showInputDialog("Enter a line"); // Remove white spaces from both sides str = str.trim(); // Count characters int length = str.length(); System.out.println("Length is: " + length); // Get the fifth character if (length >= 5) System.out.println("Fifth character is: " + str.charat(4)); else System.out.println("The fifth character does not exist"); System.out.println("Uppercase: " + str.touppercase()); System.out.println("Lowercase: " + str.tolowercase()); Comparing Strings Method Description equals(s1) Returns true if this string is equal to string s1. equalsignorecase(s1) Returns true if this string is equal to string s1; it is case insensitive. compareto(s1) Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1. comparetoignorecase(s1) Same as compareto except that the comparison is case insensitive. startswith(prefix) Returns true if this string starts with the specified prefix. endswith(suffix) Returns true if this string ends with the specified suffix. contains(s1) Returns true if s1 is a substring in this string. 7
Obtaining Substrings You can obtain a substring from a string using the substring method. For example: String message = "Welcome to Java"; String message = message.sustring(0, 11)+"HTML"; The string message now becomes "Welcome to HTML". Note that the last character (11) is excluded. Finding a Character or a Substring in a String The String class provides several versions of indexof and lastindexof methods to find a character or a substring in a string, as shown in the following table: Method indexof(ch) indexof(ch, fromindex) indexof(s) indexof(s, fromindex) lastindexof(ch) lastindexof(ch, fromindex) Description Returns the index of the first occurrence of ch in the string. Returns the index of the first occurrence of ch after fromindex in the string. Returns the index of the first occurrence of string s in this string. Returns the index of the first occurrence of string s in this string after fromindex. Returns the index of the last occurrence of ch in the string. Returns the index of the last occurrence of ch before fromindex in this string. 8
lastindexof(s) Returns the index of the last occurrence of string s. lastindexof(s, fromindex) Returns the index of the last occurrence of string s before fromindex. Note that all the previous methods return (-1) if not matched. Examples: 11 "Welcome to Java".indexOf('W') returns 0 "Welcome to Java".indexOf('o') returns 4 "Welcome to Java".indexOf('o', 5) returns 9 "Welcome to Java".indexOf("come") returns 3 "Welcome to Java".indexOf("Java", 5) returns 11 "Welcome to Java".indexOf("java", 5) returns -1 "Welcome to Java".lastIndexOf('W') returns 0 "Welcome to Java".lastIndexOf('o') returns 9 "Welcome to Java".lastIndexOf('o', 5) returns 4 "Welcome to Java".lastIndexOf("come") returns 3 "Welcome to Java".lastIndexOf("Java") returns Example: Write a Java program to prompt the user to enter his full name as FirstName LastName, and the program prints each word in a line. Solution String s = JOptionPane.showInputDialog("Enter Full Name"); int sp = s.indexof(" "); String firstname = s.substring(0, sp); String lastname = s.substring(sp + 1); System.out.println("First Name is: " + firstname); System.out.println("Last Name is: " + lastname); Note that there is a better solution for the previous example, using StringTokenizer class, which can be used as follow: Solution using StringTokenizer String s = JOptionPane.showInputDialog("Enter Full Name"); StringTokenizer st = new StringTokenizer(s, " "); String token; while (st.hasmoretokens()) { token = st.nexttoken(); System.out.println(token); } 9
10
Exercises: Part 1: Write a program that prompts the user to enter a character c and check which character is entered: If 'U', then generate a random uppercase letter. If 'L', then generate a random lowercase letter. Your program should ignore the case of the character (uppercase = lowercase). Else, print: (Your character\ "o"). replace o with the input character. Sample Input U L X Sample Output Randomly generated uppercase letter is: "M" Randomly generated uppercase letter is: "g" Your character\ "x" Hint: to generate a random number r in range a <= r <= b, use the formula: int r = (int)(math.random() * (b a + 1) + a); Part 2: (Evaluate simple expression) Write a program to prompt the user to enter a simple equation with one operator (*, /, +, -, %), and two operands (decimal numbers) (Ex. 5 * 6.3 ), and output the result of the expression. Note that there can be more than one white space between operator and operands. Example: 11
Part 3: (English words without vowels) Write a program that reads an English word and check if it contains vowels (a, e, i, o, u). If so, output Contains vowels, else, output No vowels found. Sample Input Sample Output Java Contains vowels Sky No vowels found Hint: to delete a specific character from a string, then replace it with an empty string(""). Example: String s = "Hello World"; S = s.replaceall("rl", ""); As a result: S = "Hello Wod"; 12