ch09:String and Text I/O

9-1 Introduction

9-2 The String Class

9-2-1 Constructing a String 建構字串

9-2-2 Immutable Strings and Interned Strings 字串內容恆永遠(不會改變)

A String object is immutable; its contents cannot be changed

String s = "Java";
s = "HTML"; // original "Java" not changed

p.327 Figure 9.1 Strings are immutable; once created, their contents cannot be changed

p.327 Figure 9.2 interned string instance

String s1 = "SCU CSIM";
String s2 = new String("SCU CSIM");
String s3 = "SCU CSIM";
System.out.printf("s1=[%s] s2=[%s] s3=[%s]\n", s1, s2, s3);
System.out.printf("1 s1==s2 is %b\n", s1 == s2);
System.out.printf("2 s1==s3 is %b\n", s1 == s3);
System.out.printf("3 s1 equals s2 is %b\n", s1.equals(s2));
System.out.printf("4 s1 equals s3 is %b\n", s1.equals(s3));

9-2-3 String Comparisons 字串比較

p.327 Figure 9.2 The String class contains the methods for comparing strings

if (s1 == s2) {
	System.out.println("s1 s2 相同字串物件");
} else {
	System.out.println("s1 s2 不同字串物件");
}
if (s1.equals(s2)) {
	System.out.println("s1 s2 字串內容相等");
} else {
	System.out.println("s1 s2 字串內容不相等");
}

p.328 Caution 不可以使用 < > 來比較字串,需要使用 compareTo

p.328 Note equals : true, false; compareTo : <0, 0, >0

9-2-4 String Length, Characters, and Combining Strings 字串長度、取得字元,字串結合

p.329 Figure 9.3 The String class contains the methods for getting string length, individual characters, and combining string

p.329 Caution string charAt from 0 to length()-1

s1 = "All";
s2 = "Pass";

s3 = s1.concat(s2);

s3 = s1 + " " + s2;

9-2-5 Obtaining Substrings 取得子字串

p.330 Figure 9.5 The String class contains the methods for obtaining substrings. substring

p.330 Figure 9.6 The substring method obtains a substring from a string

9-2-6 Converting, Replacing, and Splitting Strings 轉換、替換、分割字串

p.331 Figure 9.7 The String class contains the methods for converting, replacing, and splitting strings.

9-2-7 Matching, Replacing and Splitting by Patterns 藉由樣式來配對、替換、分割 字串

參考 regular expression (RE)

9-2-8 Finding a Character or a Substring in a String 在字串中找字元或子字串

p.333 Figure 9.8 The String class contains the methods for matching substrings.

9-2-9 Conversion between Strings and Arrays 字串與陣列之間的轉換

9-2-10 Converting Characters and Numeric Values to Strings 將字元與數值轉換為字串

9-2-11 Formatting Strings 字串的格式化

s = String.format("height=%d, weight=%.1f", 185, 72.5);

9-2-12 Problem: Checking Palindromes 問題:檢查字串是否迴文

參考 p.334 程式 Listing 9.1 CheckPalindrome.java

9-2-13 Problem: Converting Hexadecimals to Decimals

參考 p.336 程式 Listing 9.2 HexToDecimalConversion.java

9-3 The InetAddress Class

9-4 Serving Multiple Clients

9-5 Applet Clients

9-6 Sending and Receiving Objects

9-7 Retrieving Files from Web Servers

9-8 JEditorPane

9-9 Case Study: Distributed TicTacToe Games