Chapter 9 Strings Lecture notes for computer programming

  • Slides: 52
Download presentation
Chapter 9 Strings Lecture notes for computer programming 1 Faculty of Engineering and Information

Chapter 9 Strings Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Motivations Often you encounter the problems that involve string processing and file input and

Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write a program to replace all occurrences of a word with a new word in a file. How do you solve this problem? This chapter introduces strings and text files, which will enable you to solve this problem. 2 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Objectives § § § § § To use the String class to process fixed

Objectives § § § § § To use the String class to process fixed strings (§ 9. 2). To construct strings (§ 9. 2. 1). To understand that strings are immutable and to create an interned string (§ 9. 2. 2). To compare strings (§ 9. 2. 3). To get string length and characters, and combine strings (§ 9. 2. 4). To obtain substrings (§ 9. 2. 5). To convert, replace, and split strings (§ 9. 2. 6). To match, replace, and split strings by patterns (§ 9. 2. 7). To search for a character or substring in a string (§ 9. 2. 8). To convert between a string and an array (§ 9. 2. 9). To convert characters and numbers into a string (§ 9. 2. 10). To obtain a formatted string (§ 9. 2. 11). To check whether a string is a palindrome (§ 9. 3). To convert hexadecimal numbers to decimal numbers (§ 9. 4). To use the Character class to process a single character (§ 9. 5). To use the String. Builder and String. Buffer classes to process flexible strings (§ 9. 6). To distinguish among the String, String. Builder, and String. Buffer classes (§ 9. 2– 9. 6). To learn how to pass arguments to the main method from the command line (§ 9. 7). 3 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

The String Class • Constructing a String: – String message = "Welcome to Java“;

The String Class • Constructing a String: – String message = "Welcome to Java“; – String message = new String("Welcome to Java“); – String s = new String(); • Obtaining String length and Retrieving Individual Characters in a string • String Concatenation (concat) • Substrings (substring(index), substring(start, end)) • Comparisons (equals, compare. To) • String Conversions • Finding a Character or a Substring in a String • Conversions between Strings and Arrays • Converting Characters and Numeric Values to Strings 4 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Constructing Strings String new. String = new String(string. Literal); String message = new String("Welcome

Constructing Strings String new. String = new String(string. Literal); String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; 5 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Strings Are Immutable A String object is immutable; its contents cannot be changed. Does

Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; 6 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Trace Code String s = "Java"; s = "HTML"; 7 Liang, Introduction to Java

Trace Code String s = "Java"; s = "HTML"; 7 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Interned Strings Since strings are immutable and are frequently used, to improve efficiency and

Interned Strings Since strings are immutable and are frequently used, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. Such an instance is called interned. For example, the following statements: 8 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Examples display s 1 == s is false s 1 == s 3 is

Examples display s 1 == s is false s 1 == s 3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created. 9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String Comparisons 10 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education,

String Comparisons 10 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String Comparisons • equals String s 1 = new String("Welcome“); String s 2 =

String Comparisons • equals String s 1 = new String("Welcome“); String s 2 = "welcome"; if (s 1. equals(s 2)){ // s 1 and s 2 have the same contents } if (s 1 == s 2) { // s 1 and s 2 have the same reference } 11 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String Comparisons, cont. • compare. To(Object object) String s 1 = new String("Welcome“); String

String Comparisons, cont. • compare. To(Object object) String s 1 = new String("Welcome“); String s 2 = "welcome"; if (s 1. compare. To(s 2) > 0) { // s 1 is greater than s 2 } else if (s 1. compare. To(s 2) == 0) { // s 1 and s 2 have the same contents } else // s 1 is less than s 2 12 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String Length, Characters, and Combining Strings 13 Liang, Introduction to Java Programming, Ninth Edition,

String Length, Characters, and Combining Strings 13 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Finding String Length Finding string length using the length() method: message = "Welcome"; message.

Finding String Length Finding string length using the length() method: message = "Welcome"; message. length() (returns 7) 14 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Retrieving Individual Characters in a String • Do not use message[0] • Use message.

Retrieving Individual Characters in a String • Do not use message[0] • Use message. char. At(index) • Index starts from 0 15 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String Concatenation String s 3 = s 1. concat(s 2); String s 3 =

String Concatenation String s 3 = s 1. concat(s 2); String s 3 = s 1 + s 2; s 1 + s 2 + s 3 + s 4 + s 5 same as (((s 1. concat(s 2)). concat(s 3)). concat(s 4)). concat(s 5); 16 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Extracting Substrings 17 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education,

Extracting Substrings 17 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Extracting Substrings You can extract a single character from a string using the char.

Extracting Substrings You can extract a single character from a string using the char. At method. You can also extract a substring from a string using the substring method in the String class. String s 1 = "Welcome to Java"; String s 2 = s 1. substring(0, 11) + "HTML"; Figure 9. 6 The substring method obtains a substring from a string. 18 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Converting, Replacing, and Splitting Strings 19 Liang, Introduction to Java Programming, Ninth Edition, (c)

Converting, Replacing, and Splitting Strings 19 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Examples "Welcome". to. Lower. Case() returns a new string, welcome. "Welcome". to. Upper. Case()

Examples "Welcome". to. Lower. Case() returns a new string, welcome. "Welcome". to. Upper. Case() returns a new string, WELCOME. " Welcome ". trim() returns a new string, Welcome. "Welcome". replace('e', 'A') returns a new string, WAlcom. A. "Welcome". replace. First("e", "AB") returns a new string, WABlcome. "Welcome". replace. All("e", "AB") returns a new string, WABlcom. AB. "Welcome". replace. All("el", "AB") returns a new string, WABcome. 20 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Splitting a String[] tokens = "Java#HTML#Perl". split("#"); for (int i = 0; i <

Splitting a String[] tokens = "Java#HTML#Perl". split("#"); for (int i = 0; i < tokens. length; i++) System. out. print(tokens[i] + " "); displays Java HTML Perl 21 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Matching, Replacing and Splitting by Patterns • You can match, replace, or split a

Matching, Replacing and Splitting by Patterns • You can match, replace, or split a string by specifying a pattern. This is an extremely useful and powerful feature, commonly known as regular expression. A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. Regular expression is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III. F, “Regular Expressions, ” for further studies. "Java". matches("Java"); "Java". equals("Java"); "Java is fun". matches("Java. *"); "Java is cool". matches("Java. *"); 22 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Matching, Replacing and Splitting by Patterns The following statement evaluates to true "440 -02

Matching, Replacing and Splitting by Patterns The following statement evaluates to true "440 -02 -4534". matches("\d{3}-\d{2}-\d{4}" ) Here \d represents a single digit, and \d{3} represents three digits. 23 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Matching, Replacing and Splitting by Patterns The replace. All, replace. First, and split methods

Matching, Replacing and Splitting by Patterns The replace. All, replace. First, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c". replace. All("[$+#]", "NNN"); System. out. println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is a. NNNb. NNNNNNc 24 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Matching, Replacing and Splitting by Patterns The following statement splits the string into an

Matching, Replacing and Splitting by Patterns The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java, C? C#, C++". split("[. , : ; ? ]"); for (int i = 0; i < tokens. length; i++) System. out. println(tokens[i]); The string is split into: Java, C, C#, and C++, which are stored in array tokens. 25 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Finding a Character or a Substring in a String 26 Liang, Introduction to Java

Finding a Character or a Substring in a String 26 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Finding a Character or a Substring in a String "Welcome "Welcome to to Java".

Finding a Character or a Substring in a String "Welcome "Welcome to to Java". index. Of('W') returns 0. Java". index. Of('x') returns -1. Java". index. Of('o', 5) returns 9. Java". index. Of("come") returns 3. Java". index. Of("Java", 5) returns 11. Java". index. Of("java", 5) returns -1. Java". last. Index. Of('a') returns 14. 27 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Convert Character and Numbers to Strings The String class provides several static value. Of

Convert Character and Numbers to Strings The String class provides several static value. Of methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name value. Of with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String. value. Of(5. 44). The return value is string consists of characters ‘ 5’, ‘ 4’, and ‘ 4’. 28 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Problem: Finding Palindromes • Objective: Checking whether a string is a palindrome: a string

Problem: Finding Palindromes • Objective: Checking whether a string is a palindrome: a string that reads the same forward and backward. 29 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example to find Palindromes 1 import java. util. Scanner; 2 3 public class Check.

Example to find Palindromes 1 import java. util. Scanner; 2 3 public class Check. Palindrome { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System. in); 8 9 // Prompt the user to enter a string 10 System. out. print("Enter a string: "); 11 String s = input. next. Line(); 12 13 if (is. Palindrome(s)) 14 System. out. println(s + " is a palindrome"); 15 else 16 System. out. println(s + " is not a palindrome"); 17 } 30 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example to find Palindromes, Cont. 18 19 20 21 22 23 24 25 26

Example to find Palindromes, Cont. 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 /** Check if a string is a palindrome */ public static boolean is. Palindrome(String s) { // The index of the first character in the string int low = 0; // The index of the last character in the string int high = s. length() - 1; while (low < high) { if (s. char. At(low) != s. char. At(high)) return false; // Not a palindrome low++; high--; } return true; // The string is a palindrome } } 31 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

The Character Class 32 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson

The Character Class 32 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Examples Character char. Object = new Character('b'); char. Object. compare. To(new Character('a')) returns 1

Examples Character char. Object = new Character('b'); char. Object. compare. To(new Character('a')) returns 1 char. Object. compare. To(new Character('b')) returns 0 char. Object. compare. To(new Character('c')) returns -1 char. Object. compare. To(new Character('d') returns – 2 char. Object. equals(new Character('b')) returns true char. Object. equals(new Character('d')) returns false 33 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Problem: Counting Each Letter in a String This example gives a program that counts

Problem: Counting Each Letter in a String This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. 34 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example of Counting Each Letter in a String 1 import java. util. Scanner; 2

Example of Counting Each Letter in a String 1 import java. util. Scanner; 2 3 public class Count. Each. Letter { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System. in); 8 9 // Prompt the user to enter a string 10 System. out. print("Enter a string: "); 11 String s = input. next. Line(); 12 13 // Invoke the count. Letters method to count each letter 14 int[] counts = count. Letters(s. to. Lower. Case()); 15 16 // Display results 17 for (int i = 0; i < counts. length; i++) { 18 if (counts[i] != 0) 19 System. out. println((char)('a' + i) + " appears " + 20 counts[i] + ((counts[i] == 1) ? " time" : " times")); 21 } 22 } 35 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example of Counting Each Letter in a String, Cont. 23 24 25 26 27

Example of Counting Each Letter in a String, Cont. 23 24 25 26 27 28 29 30 31 32 33 34 35 /** Count each letter in the string */ public static int[] count. Letters(String s) { int[] counts = new int[26]; for (int i = 0; i < s. length(); i++) { if (Character. is. Letter(s. char. At(i))) counts[s. char. At(i) - 'a']++; } return counts; } } 36 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String. Builder and String. Buffer The String. Builder/String. Buffer class is an alternative to

String. Builder and String. Buffer The String. Builder/String. Buffer class is an alternative to the String class. In general, a String. Builder/String. Buffer can be used wherever a string is used. String. Builder/String. Buffer is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. 37 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

String. Builder Constructors 38 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson

String. Builder Constructors 38 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Modifying Strings in the Builder 39 Liang, Introduction to Java Programming, Ninth Edition, (c)

Modifying Strings in the Builder 39 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Examples string. Builder. append("Java"); string. Builder. insert(11, "HTML and "); string. Builder. delete(8, 11)

Examples string. Builder. append("Java"); string. Builder. insert(11, "HTML and "); string. Builder. delete(8, 11) changes the builder to Welcome Java. string. Builder. delete. Char. At(8) changes the builder to Welcome o Java. string. Builder. reverse() changes the builder to ava. J ot emocle. W. string. Builder. replace(11, 15, "HTML") changes the builder to Welcome to HTML. string. Builder. set. Char. At(0, 'w') sets the builder to welcome to Java. 40 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

The to. String, capacity, length, set. Length, and char. At Methods 41 Liang, Introduction

The to. String, capacity, length, set. Length, and char. At Methods 41 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Problem: Checking Palindromes Ignoring Non-alphanumeric Characters This example gives a program that counts the

Problem: Checking Palindromes Ignoring Non-alphanumeric Characters This example gives a program that counts the number of occurrence of each letter in a string. Assume the letters are not case-sensitive. 42 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example of Checking Palindromes Ignoring Nonalphanumeric Characters 1 import java. util. Scanner; 2 3

Example of Checking Palindromes Ignoring Nonalphanumeric Characters 1 import java. util. Scanner; 2 3 public class Palindrome. Ignore. Non. Alphanumeric { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System. in); 8 9 // Prompt the user to enter a string 10 System. out. print("Enter a string: "); 11 String s = input. next. Line(); 12 13 // Display result 14 System. out. println("Ignoring non-alphanumeric characters, nis " 15 + s + " a palindrome? " + is. Palindrome(s)); 16 } 43 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

17 18 19 20 21 22 23 24 25 26 27 28 /** Return

17 18 19 20 21 22 23 24 25 26 27 28 /** Return true if a string is a palindrome */ public static boolean is. Palindrome(String s) { // Create a new string by eliminating non-alphanumeric chars String s 1 = filter(s); // Create a new string that is the reversal of s 1 String s 2 = reverse(s 1); // Compare if the reversal is the same as the original string return s 2. equals(s 1); } 44 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

29 30 31 32 33 34 35 36 37 38 39 40 41 42

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 /** Create a new string by eliminating non-alphanumeric chars */ public static String filter(String s) { // Create a string builder String. Builder string. Builder = new String. Builder(); // Examine each char in the string to skip alphanumeric char for (int i = 0; i < s. length(); i++) { if (Character. is. Letter. Or. Digit(s. char. At(i))) { string. Builder. append(s. char. At(i)); } } // Return a new filtered string return string. Builder. to. String(); } /** Create a new string by reversing a specified string */ public static String reverse(String s) { String. Builder string. Builder = new String. Builder(s); string. Builder. reverse(); // Invoke reverse in String. Builder return string. Builder. to. String(); }} 45 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Main Method Is Just a Regular Method You can call a regular method by

Main Method Is Just a Regular Method You can call a regular method by passing actual parameters. Can you pass arguments to main? Of course, yes. For example, the main method in class B is invoked by a method in A, as shown below: 46 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Command-Line Parameters class Test. Main { public static void main(String[] args) {. . .

Command-Line Parameters class Test. Main { public static void main(String[] args) {. . . } } java Test. Main arg 0 arg 1 arg 2. . . argn 47 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Processing Command-Line Parameters In the main method, get the arguments from args[0], args[1], .

Processing Command-Line Parameters In the main method, get the arguments from args[0], args[1], . . . , args[n], which corresponds to arg 0, arg 1, . . . , argn in the command line. 48 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Problem: Calculator • Objective: Write a program that will perform binary operations on integers.

Problem: Calculator • Objective: Write a program that will perform binary operations on integers. The program receives three parameters: an operator and two integers. java Calculator "2 + 3" java Calculator "2 - 3" java Calculator "2 / 3" java Calculator "2 * 3" 49 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Example of Calculator 1 public class Calculator { 2 /** Main method */ 3

Example of Calculator 1 public class Calculator { 2 /** Main method */ 3 public static void main(String[] args) { 4 // Check number of strings passed 5 if (args. length != 1) { 6 System. out. println( 7 "Usage: java Calculator "operand 1 operator operand 2""); 8 System. exit(0); 9 } 10 11 // The result of the operation 12 int result = 0; 13 14 // The result of the operation 15 String[] tokens = args[0]. split(" "); 50 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

16 17 18 19 20 21 22 23 24 25 26 27 28 29

16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Determine the operator switch (tokens[1]. char. At(0)) { case '+': result = Integer. parse. Int(tokens[0]) + Integer. parse. Int(tokens[2]); break; case '-': result = Integer. parse. Int(tokens[0]) – Integer. parse. Int(tokens[2]); break; case '*': result = Integer. parse. Int(tokens[0]) * Integer. parse. Int(tokens[2]); break; case '/': result = Integer. parse. Int(tokens[0]) / Integer. parse. Int(tokens[2]); } // Display result System. out. println(tokens[0] + ' ' + tokens[1] + ' ' + tokens[2] + " = " + result); } } 51 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Regular Expression Syntax 52 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson

Regular Expression Syntax 52 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.