Java课件第二章补充字符串.ppt_第1页
Java课件第二章补充字符串.ppt_第2页
Java课件第二章补充字符串.ppt_第3页
Java课件第二章补充字符串.ppt_第4页
Java课件第二章补充字符串.ppt_第5页
已阅读5页,还剩37页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1,I Constructing a String,II String Methods,2,The String Class,Constructing a String: Obtaining String length and Retrieving Individual Characters in a string String String Concatenation (concat) Substrings (substring(index), substring(start, end) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings,3,Constructing Strings,Format: String newString = new String(stringLiteral); String message = “stringLiteral“;,Example: String message = new String(“Hello“); String message = “Welcome to Java“;,4,Storage String pool & stack & heap String pool(字符串池): JVM has a String pool, it saves a lot of String objects that created by shorthand initializer. Data sharing Stack (栈) : Store primitive data(char、byte、short、int、long、float、double、boolean)and constructor. Data sharing. heap(堆):Store Object.,5,String str=new String(“abc“);,Difference between new and shorthand initializer,Question: How many String objects are created?,Two,Constructor: public String(String original) /other code . ,Note:The parameter is a String object,6,String a= “abc“; String b= “abc“;,Difference between new and shorthand initializer,Question: How many String objects are created?,One,7,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.,8,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“;,?,9,0x1245,s,Trace Code,String s = “Java“; s = “HTML“;,After executing s=“java”;,After executing s=“HTML”;,10,Canonical Strings(规范字符串),canonical string: if two String objects were created with the same string literal using the shorthand initializer, then the JVM stores them in the same object. This string literal is called canonical string.,improve efficiency and save memory,Using String objects intern method to return a canonical string,11,intern: public native String intern() Returns a canonical representation for the string object. If s and t are strings such that s.equals(t), it is guaranteed that ern() = ern().,Canonical Strings,12,String s = “Welcome to Java“; String s1 = new String(“Welcome to Java“); String s2 = ern(); String s3 = “Welcome to Java“; System.out.println(“s1 = s is “ + (s1 = s); System.out.println(“s2 = s is “ + (s2 = s); System.out.println(“s = s3 is “ + (s = s3);,Examples,display s1 = s is false s2 = s is true s = s3 is true,13,Finding String Length,Finding string length using the length() method:,Example:message = “Welcome“; message.length() (returns 7),14,Retrieving Individual Characters in a String,Do not use message0 Use message.charAt(index) public char charAt(int index) Returns the character at the specified index. An index ranges from 0 to length() - 1. Index starts from 0,charAt方法的使用,public String concat(String str) Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this object is returned. Parameters: the String that is concatenated to the end of this String. Returns: a string that represents the concatenation of this objects characters followed by the string arguments characters.,String Concatenation,16,String Concatenation,String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (s1.concat(s2).concat(s3).concat(s4).concat(s5);,17,public String substring(int beginIndex) Returns a new string that is a substring of this string. The substring begins at the specified index and extends to the end of this string. public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Parameters: the beginning index, inclusive. Returns: the specified substring. Throws: StringIndexOutOfBoundsException if the beginIndex is out of range.,Extracting Substrings,18,Extracting Substrings,String is an immutable class; its values cannot be changed individually. String s1 = “Welcome to Java“; String s2 = s1.substring(0, 11) + “HTML“;,19,String Comparisons,equals String s1 = new String(“Welcome“); String s2 = “Welcome“; if (s1.equals(s2) / s1 and s2 have the same contents if (s1 = s2) / s1 and s2 have the same reference ,20,String Comparisons, cont.,compareTo(Object object) String s1 = new String(“Welcome“); String s2 = “welcome“; if (pareTo(s2) 0) / s1 is greater than s2 else if (pareTo(s2) = 0) / s1 and s2 have the same contents else / s1 is less than s2,21,String Conversions,The contents of a string cannot be changed once the string is created. But you can convert a string to a new string using the following methods: toLowerCase toUpperCase trim replace(oldChar, newChar),22,Finding a Character or a Substring in a String,“Welcome to Java“.indexOf(W) returns 0. “Welcome to Java“.indexOf(x) returns -1. “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(a) returns 14.,23,Convert Character and Numbers to Strings,The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueOf with different argument types char, char, double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters 5, ., 4, and 4.,24,The Character Class,25,Examples,Character charObject = new Character(b); charOpareTo(new Character(a) returns 1 charOpareTo(new Character(b) returns 0 charOpareTo(new Character(c) returns -1 charOpareTo(new Character(d) returns 2 charObject.equals(new Character(b) returns true charObject.equals(new Character(d) returns false,26,The StringBuffer Class,The StringBuffer class is an alternative to the String class. In general, a string buffer can be used wherever a string is used. StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer. However, the value of a String object is fixed once the string is created.,27,28,StringBuffer Constructors,public StringBuffer() No characters, initial capacity 16 characters. public StringBuffer(int length) No characters, initial capacity specified by the length argument. public StringBuffer(String str) Represents the same sequence of characters as the string argument. Initial capacity 16 plus the length of the string argument.,29,Appending New Contents into a String Buffer,StringBuffer strBuf = new StringBuffer(); strBuf.append(“Welcome“); strBuf.append( ); strBuf.append(“to“); strBuf.append( ); strBuf.append(“Java“);,30,Example:,String s=“ABCD”; s.concat(“E”); s.replace(C,F); System.out.println(s); What will be printed out? A. Compilation Error says that String is immutable B. ABFDE C. ABCDE D. ABCD,31,class Happy static StringBuffer sb1=new StringBuffer(“A“); static StringBuffer sb2=new StringBuffer(“B“); public static void main(String args) Happy h=new Happy(); h.methodA(sb1,sb2); System.out.println(sb1+“ “+sb2); public void methodA(StringBuffer x,StringBuffer y) y.append(x); What will be the output?,32,The StringTokenizer Class,33,Examples 1,String s = “Java is cool.“; StringTokenizer tokenizer = new StringTokenizer(s); System.out.println(“The total number of tokens is “ + tokenizer.countTokens(); while (tokenizer.hasMoreTokens() System.out.println(tokenizer.nextToken();,The total number of tokens is 3 Java is cool.,The code displays,34,Examples 2,String s = “Java is cool.“; StringTokenizer tokenizer = new StringTokenizer(s, “ac“); System.out.println(“The total number of tokens is “ + tokenizer.countTokens(); while (tokenizer.hasMoreTokens() System.out.println(tokenizer.nextToken();,The total number of tokens is 4 J v is ool.,The code displays,35,Examples 3,String s = “Java is cool.“; StringTokenizer tokenizer = new StringTokenizer(s, “ac“, true); System.out.println(“The total number of tokens is “ + tokenizer.countTokens(); while (tokenizer.hasMoreTokens() System.out.println(tokenizer.nextToken();,The total number of tokens is 7 J a v a is c ool.,The code displays,36,No no-arg Constructor in StringTokenizer,The StringTokenizer class does not have a no-arg constructor. Normally it is a good programming practice to provide a no-arg constructor for each class. On rare occasions, however, a no-arg constructor does not make sense. StringTokenizer is such an example. A StringTokenizer object must be created for a string, which should be passed as an argument from a constructor.,37,The Scanner Class,The delimiters are single characters in StringTokenizer. You can use the new JDK 1.5 java.util.Scanner class to specify a word as a delimiter.,JDK 1.5 Feature,String s = “Welcome to Java! Java is fun! Java is cool!“; Scanner scanner = new Scanner(s); scanner.useDelimiter(“Java“); while (scanner.hasNext() System.out.println(scanner.next();,Creates an instance of Scanner for the string.,Sets “Java” as a delimiter.,hasNext() returns true if there are still more tokens left.,The next() method returns a token as a string.,Welcome to ! is fun! is cool!,38,Scanning Primitive Type Values,If a token is a primitive data type value, you can use the methods nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), or nextBoolean() to obtain it. For example, the following code adds all numbers in the string. Note that the delimiter is space by default.,String s = “1 2 3 4“; Scanner scanner = new Scanner(s); int sum = 0; while (scanner.hasNext() sum += scanner.nextInt(); System.out.println(“Sum is “ + sum);,JDK 1.5 Feature,39,Console Input Using Scanner,Another important a

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论