Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java 2013.01.04.

Similar presentations


Presentation on theme: "Java 2013.01.04."— Presentation transcript:

1 Java

2 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

3 The String Class A string is a sequence of characters.
The String class has 11 constructors and more than 40 methods. Declaration: String S = new String(“Hello Java”); String S = “Hello Java”; Char[] C = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ’ ’, ‘J’, ‘a’, ‘v’, ‘a’ }; String S = new String(C);

4 Immutable Strings and Interned Strings
A string object is immutable; its content cannot be changed. String S = “Java”; S = “html”; S :String S X :String String object for “Java” String object for “Java” :String String object for “html”

5 String Comparisons Java.lang.String S1.equals(S2): boolean
S1.equalsIgnoreCase(S2): boolean S1.compareTo(S2): int S1.compareToIgnoreCase(S2): int . 推薦網站: (課本p.327)

6 String Length, Characters, and Combining Strings
Java.lang.String S.length(): int S.charAt(index: int): char S.concat(S2): String S.length() = 10 H e l l o J a v a S.charAt(0) S.charAt(9) A String object is presented using an array internally. (課本p.365)

7 Obtaining Substrings Java.lang.String
S.substring(beginIndex: int): String S.substring(beginIndex: int , endIndex: int): String H e l l o J a v a S.substring(0,5) (課本p.366)

8 程式練習: 使用substring method, 印出S1中的第0~4個characters

9 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.367)

10 程式練習: 1. 將S1轉成lowercase印出 2. 將S2轉成uppercase印出 3. 將S1中的”JAVA”子字串
4. 嘗試字串分割 String[] names = S1.split(" "); for(String name:names) { System.out.println(name); }

11 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.368)

12 程式練習: 從S1找出子字串”JAVA”印出回傳值

13 Practice (Anagrams) Write a method that checks whether two words are anagrams. Two words are anagrams if they contain the same letters in any order. For example,"silent" and "listen" are anagrams. The header of the method is as follows: public static boolean isAnagram(String s1, String s2) Write a test program that prompts the user to enter two strings and, if they are anagrams, displays "anagram", otherwise displays "not anagram".

14 Ppt下載:


Download ppt "Java 2013.01.04."

Similar presentations


Ads by Google