java @ch9. string and text i/o 2010.12.17. outline the string class immutable strings and interned...
Post on 21-Dec-2015
233 views
TRANSCRIPT
Outline
• The String Class• Immutable Strings and Interned Strings• String Comparisons• String Length, Characters, and Combining Strings• Obtaining Substrings• Converting, replaceing, and Splitting Strings• Finding a Character or a Substring in a String• The File Class
[Sample code]
TestFileClass.java
The String Class
A string is a sequence of characters.
The String class has 11 constructors and more than 40 methods.
Declaration:
1. String S = new String(“Hello Java”);
2. String S = “Hello Java”;
3. Char[] C = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ’ ’, ‘J’, ‘a’, ‘v’, ‘a’ };
String S = new String(C);
Immutable Strings and Interned Strings
A string object is immutable; its content cannot be changed.
String object for “Java”
:StringS
String object for “Java”
:StringS
String object for “html”
:String
S = “html”;String S = “Java”;
X
S1.equals(S2): boolean
S1.equalsIgnoreCase(S2): boolean
S1.compareTo(S2): int
S1.compareToIgnoreCase(S2): int...
Java.lang.String
推薦網站 : http://www.tutorialspoint.com/java/java_strings.htm
String Comparisons
( 課本 p.327)
String Length, Characters, and Combining Strings
H e l l o J a v a
0 1 2 3 4 5 6 7 8 9
S.charAt(0)
Java.lang.String
S.length(): intS.charAt(index: int): charS.concat(S2): String
S.length() = 10
S.charAt(9)
A String object is presented using an array internally. ( 課本 p.329)
程式練習 :
1. 宣告一個 String object S1 = “HELLO JAVA ”
2. 宣告一個 String object S2 = “i love Java”
3. 印出 S1 的長度4. 印出 S1 的第 7 個 char 的內容5. 用 equals 比較 S1 和 S2, 並印出 true 或
false
6. 用 concat 將 S1 和 S2 字串連接起來 , 並印出
Obtaining Substrings
Java.lang.String
S.substring(beginIndex: int): StringS.substring(beginIndex: int , endIndex: int): String
H e l l o J a v a
0 1 2 3 4 5 6 7 8 9
S.substring(0,5)
( 課本 p.330)
Converting, replaceing, and Splitting Strings
Java.lang.String
S.toLowerCase(): String
S.toUpperCase(): String
S.trim(): String
S.replace(oldchar, newchar): String
S.replaceFirst(oldString, newString): String
S.replaceAll(oldString, newString): String
S.split (delimiter: String): String[ ]( 課本 p.331)
程式練習 :
1. 將 S1 轉成 lowercase 印出2. 將 S2 轉成 uppercase 印出3. 將 S1 中的” JAVA” 子字串 換成” C++” 印出4. 嘗試字串分割
String[] names = S1.split(" ");
for(String name:names)
{
System.out.println(name);
}
Finding a Character or a Substring in a String
Java.lang.String
“JAVA”.indexOf(‘J’) return 0.
“JAVA”.indexOf(‘A’) return 1.
“JAVA”.indexOf(‘A’,2) return 3.
“JAVA”.indexOf(”VA”) return 2.
“JAVA”.indexOf(”ABC”,2) return -1.
“JAVA”.lastIndexOf(‘A’) return 3.... ( 課本 p.332)
The File Class
Create File object.
EX:
java.io.File file = new java.io.File(“abc.txt”);
Writing Data Using PrintWriter.
EX:
PrintWriter output = new PrintWriter(file);
( 課本 p.349)