版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、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 F
2、inding 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
3、message = Welcome to Java;,4,Storage String pool ,Difference between new and shorthand initializer,Question: How many String objects are created?,Two,Constructor: publicString(Stringoriginal) /othercode. ,Note:The parameter is a String object,6,Stringa= abc; String b= abc;,Difference between new and
4、 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 c
5、annot be changed.,Does the following code change the contents of the string String s = Java; s = HTML;,?,9,0 x1245,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 sam
6、e 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 canonic
7、al 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
8、= 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,Ret
9、rieving 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方法的使用,15,public String concat(String str) Concatenates the specified s
10、tring 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.
11、,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 th
12、e 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
13、, 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 valuescannot be changed individually. String s1 = Welcome to Java; String s2 = s1.substring(0, 11
14、) + 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 = we
15、lcome; 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
16、: 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) r
17、eturns 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 hav
18、e 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 = ne
19、w 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
20、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 contentsinto a string buffer. However, the value ofa String object is fixed once the string is cre
21、ated.,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 charactersas the string argumen
22、t. Initial capacity 16plus 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.rep
23、lace(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();
24、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
25、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
26、 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.pr
27、intln(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 c
28、onstructor. 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 argumen
29、t 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.
30、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,Scann
31、ing 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 application of the Scanner class is to read
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 医用吸引器生产线建设项目可行性研究报告
- 医学26年:更年期综合征诊疗 查房课件
- 老年慢性病管理的医疗资源协同网络
- 2026-2032年中国机动车污染防治行业市场动态分析及投资趋势研判报告
- 初中生2025年实践活动说课稿自然观察
- 小学生分享合作主题班会说课稿
- 断桥门窗安装合同履行与合同解除条件合同三篇
- 糖尿病合并心血管病的综合防控体系
- 第3课 画正多边形说课稿2025学年小学信息技术电子工业版内蒙古六年级下册-电子工业版(内蒙古)
- 2026年译林版thenandnow说课稿
- 2025年神农架林区公安局招聘辅警真题
- 胸痹患者中医护理评估与干预
- 2026年4月福建厦门市思明区部分单位联合招聘非在编人员4人笔试模拟试题及答案解析
- 江苏苏豪控股集团秋招面笔试题及答案
- 24J113-1 内隔墙-轻质条板(一)
- 律师事务所内部惩戒制度
- 高中英语课堂形成性评价与听力理解能力提升教学研究课题报告
- 校园校园环境智能监测系统方案
- (2025年)资阳市安岳县辅警考试公安基础知识考试真题库及参考答案
- 小学音乐中多元文化音乐元素的融合与创新教学课题报告教学研究课题报告
- 心脏再同步化治疗的精准医疗策略
评论
0/150
提交评论