java语言程序设计基础篇第八版课件PPT第九章机械工业出版报社李娜译_第1页
java语言程序设计基础篇第八版课件PPT第九章机械工业出版报社李娜译_第2页
java语言程序设计基础篇第八版课件PPT第九章机械工业出版报社李娜译_第3页
java语言程序设计基础篇第八版课件PPT第九章机械工业出版报社李娜译_第4页
java语言程序设计基础篇第八版课件PPT第九章机械工业出版报社李娜译_第5页
已阅读5页,还剩53页未读 继续免费阅读

下载本文档

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

文档简介

1、1chapter 9 strings and text i/o2motivationsoften you encounter the problems that involve string processing and file input and output. suppose you need to write a program to replace all occurrences of a word with a new word in a file. how do you solve this problem? this chapter introduces strings and

2、 text files, which will enable you to solve this problem.3objectivesfto use the string class to process fixed strings (9.2).fto use the character class to process a single character (9.3).fto use the stringbuilder/stringbuffer class to process flexible strings (9.4). fto distinguish among the string

3、, stringbuilder, and stringbuffer classes (9.2-9.4).fto learn how to pass arguments to the main method from the command line (9.5).fto discover file properties and to delete and rename files using the file class (9.6).fto write data to a file using the printwriter class (9.7.1). fto read data from a

4、 file using the scanner class (9.7.2).f(gui) to open files using a dialog box (9.8).4the string classfconstructing a string: string message = welcome to java“;string message = new string(welcome to java“); string s = new string();fobtaining string length and retrieving individual characters in a str

5、ingfstring concatenation (concat)fsubstrings (substring(index), substring(start, end)fcomparisons (equals, compareto)fstring conversionsffinding a character or a substring in a stringfconversions between strings and arraysfconverting characters and numeric values to strings5constructing stringsstrin

6、g newstring = new string(stringliteral); string message = new string(welcome to java);since strings are used frequently, java provides a shorthand initializer for creating a string:string message = welcome to java;6strings are immutablea string object is immutable; its contents cannot be changed. do

7、es the following code change the contents of the string? string s = java; s = html;7trace code string s = java; s = html; : string string object for java s after executing string s = java; after executing s = html; : string string object for java : string string object for html contents cannot be ch

8、anged this string object is now unreferenced s animation8trace code string s = java; s = html; : string string object for java s after executing string s = java; after executing s = html; : string string object for java : string string object for html contents cannot be changed this string object is

9、 now unreferenced s animation9interned stringssince strings are immutable and are frequently used, to improve efficiency and save memory, the jvm uses a unique instance for string literals with the same character sequence. such an instance is called interned. for example, the following statements: 1

10、0examplesdisplay s1 = s is false s1 = s3 is truea 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. string s1 = welcome to java; string s2 = new string(welcome to java); string s3 = welcome to jav

11、a; system.out.println(s1 = s2 is + (s1 = s2); system.out.println(s1 = s3 is + (s1 = s3); : string interned string object for welcome to java : string a string object for welcome to java s1 s2 s3 11trace code string s1 = welcome to java; string s2 = new string(welcome to java); string s3 = welcome to

12、 java; : string interned string object for welcome to java s1 animation12trace code string s1 = welcome to java; string s2 = new string(welcome to java); string s3 = welcome to java; : string interned string object for welcome to java : string a string object for welcome to java s1 s2 13trace code s

13、tring s1 = welcome to java; string s2 = new string(welcome to java); string s3 = welcome to java; : string interned string object for welcome to java : string a string object for welcome to java s1 s2 s3 14string comparisons java.lang.string +equals(s1: string): boolean +equalsignorecase(s1: string)

14、: boolean +compareto(s1: string): int +comparetoignorecase(s1: string): int +regionmatches(toffset: int, s1: string, offset: int, len: int): boolean +regionmatches(ignorecase: boolean, toffset: int, s1: string, offset: int, len: int): boolean +startswith(prefix: string): boolean +endswith(suffix: st

15、ring): boolean returns true if this string is equal to string s1. returns true if this string is equal to string s1 case-insensitive. returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1. same as compareto except tha

16、t the comparison is case-insensitive. returns true if the specified subregion of this string exactly matches the specified subregion in string s1. same as the preceding method except that you can specify whether the match is case-sensitive. returns true if this string starts with the specified prefi

17、x. returns true if this string ends with the specified suffix. 15string comparisonsfequalsstring 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 16string comparisons, cont.fcompareto(object object)st

18、ring 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 s217string length, characters, and combining strings java.lang.string +length(): int +charat(index: int): char +concat(s1:

19、string): string returns the number of characters in this string. returns the character at the specified index from this string. returns a new string that concatenate this string with string s1. string. 18finding string lengthfinding string length using the length() method:message = welcome;message.l

20、ength() (returns 7)19retrieving individual characters in a stringfdo not use message0fuse message.charat(index)findex starts from 0 w e l c o m e t o j a v a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 message indices message.charat(0) message.charat(14) message.length() is 15 20string concatenationstring s3

21、 = s1.concat(s2);string s3 = s1 + s2;s1 + s2 + s3 + s4 + s5 same as(s1.concat(s2).concat(s3).concat(s4).concat(s5);21extracting substrings java.lang.string +substring(beginindex: int): string +substring(beginindex: int, endindex: int): string returns this strings substring that begins with the chara

22、cter at the specified beginindex and extends to the end of the string, as shown in figure 8.6. returns this strings substring that begins at the specified beginindex and extends to the character at index endindex 1, as shown in figure 8.6. note that the character at endindex is not part of the subst

23、ring. 22extracting substringsyou can extract a single character from a string using the charat method. you can also extract a substring from a string using the substring method in the string class. string s1 = welcome to java;string s2 = s1.substring(0, 11) + html; w e l c o m e t o j a v a 0 1 2 3

24、4 5 6 7 8 9 10 11 12 13 14 message indices message.substring(0, 11) message.substring(11) 23converting, replacing, and splitting strings java.lang.string +tolowercase(): string +touppercase(): string +trim(): string +replace(oldchar: char, newchar: char): string +replacefirst(oldstring: string, news

25、tring: string): string +replaceall(oldstring: string, newstring: string): string +split(delimiter: string): string returns a new string with all characters converted to lowercase. returns a new string with all characters converted to uppercase. returns a new string with blank characters trimmed on b

26、oth sides. returns a new string that replaces all matching character in this string with the new character. returns a new string that replaces the first matching substring in this string with the new substring. returns a new string that replace all matching substrings in this string with the new sub

27、string. returns an array of strings consisting of the substrings split by the delimiter. 24exampleswelcome.tolowercase() returns a new string, welcome.welcome.touppercase() returns a new string, welcome. welcome .trim() returns a new string, welcome.welcome.replace(e, a) returns a new string, walcom

28、a.welcome.replacefirst(e, ab) returns a new string, wablcome.welcome.replace(e, ab) returns a new string, wablcomab.welcome.replace(el, ab) returns a new string, wablcome.25splitting a stringstring tokens = java#html#perl.split(#, 0);for (int i = 0; i tokens.length; i+) system.out.print(tokensi + );

29、java html perldisplays26matching, replacing and splitting by patterns you can match, replace, or split a string by specifying a pattern. this is an extremely useful and powerful feature, commonly known as regular expression. regular expression is complex to beginning students. for this reason, two s

30、imple patterns are used in this section. please refer to supplement iii.f, “regular expressions,” for further studies. java.matches(java);java.equals(java);java is fun.matches(java.*);java is cool.matches(java.*);27matching, replacing and splitting by patterns the replaceall, replacefirst, and split

31、 methods can be used with a regular expression. for example, the following statement returns a new string that replaces $, +, or # in a+b$#c by the string nnn.string s = a+b$#c.replaceall($+#, nnn);system.out.println(s);here the regular expression $+# specifies a pattern that matches $, +, or #. so,

32、 the output is annnbnnnnnnc.28matching, replacing and splitting by patterns the following statement splits the string into an array of strings delimited by some punctuation marks.string tokens = java,c?c#,c+.split(.,:;?); for (int i = 0; i tokens.length; i+) system.out.println(tokensi);29finding a c

33、haracter or a substring in a string java.lang.string +indexof(ch: char): int +indexof(ch: char, fromindex: int): int +indexof(s: string): int +indexof(s: string, fromindex: int): int +lastindexof(ch: int): int +lastindexof(ch: int, fromindex: int): int +lastindexof(s: string): int +lastindexof(s: st

34、ring, fromindex: int): int returns the index of the first occurrence of ch in the string. returns -1 if not matched. returns the index of the first occurrence of ch after fromindex in the string. returns -1 if not matched. returns the index of the first occurrence of string s in this string. returns

35、 -1 if not matched. returns the index of the first occurrence of string s in this string after fromindex. returns -1 if not matched. returns the index of the last occurrence of ch in the string. returns -1 if not matched. returns the index of the last occurrence of ch before fromindex in this string

36、. returns -1 if not matched. returns the index of the last occurrence of string s. returns -1 if not matched. returns the index of the last occurrence of string s before fromindex. returns -1 if not matched. 30finding a character or a substring in a stringwelcome to java.indexof(w) returns 0.welcome

37、 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. 31convert character and numbers to stringsthe string class

38、 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.

39、valueof(5.44). the return value is string consists of characters 5, ., 4, and 4. 32problem: finding palindromesfobjective: checking whether a string is a palindrome: a string that reads the same forward and backward.33the character class java.lang.character +character(value: char) +charvalue(): char

40、 +compareto(anothercharacter: character): int +equals(anothercharacter: character): boolean +isdigit(ch: char): boolean +isletter(ch: char): boolean +isletterordigit(ch: char): boolean +islowercase(ch: char): boolean +isuppercase(ch: char): boolean +tolowercase(ch: char): char +touppercase(ch: char)

41、: char constructs a character object with char value returns the char value from this object compares this character with another returns true if this character equals to another returns true if the specified character is a digit returns true if the specified character is a letter returns true if th

42、e character is a letter or a digit returns true if the character is a lowercase letter returns true if the character is an uppercase letter returns the lowercase of the specified character returns the uppercase of the specified character 34examplescharacter charobject = new character(b);charopareto(

43、new character(a) returns 1charopareto(new character(b) returns 0charopareto(new character(c) returns -1charopareto(new character(d) returns 2charobject.equals(new character(b) returns truecharobject.equals(new character(d) returns false35problem: counting each letter in a stringthis example gives a

44、program that counts the number of occurrence of each letter in a string. assume the letters are not case-sensitive. 36stringbuilder and stringbufferthe stringbuilder/stringbuffer class is an alternative to the string class. in general, a stringbuilder/stringbuffer can be used wherever a string is us

45、ed. stringbuilder/stringbuffer is more flexible than string. you can add, insert, or append new contents into a string buffer, whereas the value of a string object is fixed once the string is created. 37stringbuilder constructors java.lang.stringbuilder +stringbuilder() +stringbuilder(capacity: int)

46、 +stringbuilder(s: string) constructs an empty string builder with capacity 16. constructs a string builder with the specified capacity. constructs a string builder with the specified string. 38modifying strings in the builder java.lang.stringbuilder +append(data: char): stringbuilder +append(data:

47、char, offset: int, len: int): stringbuilder +append(v: aprimitivetype): stringbuilder +append(s: string): stringbuilder +delete(startindex: int, endindex: int): stringbuilder +deletecharat(index: int): stringbuilder +insert(index: int, data: char, offset: int, len: int): stringbuilder +insert(offset

48、: int, data: char): stringbuilder +insert(offset: int, b: aprimitivetype): stringbuilder +insert(offset: int, s: string): stringbuilder +replace(startindex: int, endindex: int, s: string): stringbuilder +reverse(): stringbuilder +setcharat(index: int, ch: char): void appends a char array into this s

49、tring builder. appends a subarray in data into this string builder. appends a primitive type value as a string to this builder. appends a string to this string builder. deletes characters from startindex to endindex. deletes a character at the specified index. inserts a subarray of the data in the a

50、rray to the builder at the specified index. inserts data into this builder at the position offset. inserts a value converted to a string into this builder. inserts a string into this builder at the position offset. replaces the characters in this builder from startindex to endindex with the specifie

51、d string. reverses the characters in the builder. sets a new character at the specified index in this builder. 39examplesstringbuilder.append(java);stringbuilder.insert(11, html and );stringbuilder.delete(8, 11) changes the builder to welcome java.stringbuilder.deletecharat(8) changes the builder to

52、 welcome o java.stringbuilder.reverse() changes the builder to avaj ot emoclew.stringbuilder.replace(11, 15, html) changes the builder to welcome to html.stringbuilder.setcharat(0, w) sets the builder to welcome to java. 40the tostring, capacity, length, setlength, and charat methods java.lang.strin

53、gbuilder +tostring(): string +capacity(): int +charat(index: int): char +length(): int +setlength(newlength: int): void +substring(startindex: int): string +substring(startindex: int, endindex: int): string +trimtosize(): void returns a string object from the string builder. returns the capacity of

54、this string builder. returns the character at the specified index. returns the number of characters in this builder. sets a new length in this builder. returns a substring starting at startindex. returns a substring from startindex to endindex-1. reduces the storage size used for the string builder.

55、 41problem: checking palindromes ignoring non-alphanumeric charactersthis example gives a program that counts the number of occurrence of each letter in a string. assume the letters are not case-sensitive. 42main method is just a regular method public class a public static void main(string args) str

56、ing strings = new york, boston, atlanta; b.main(strings); class b public static void main(string args) for (int i = 0; i args.length; i+) system.out.println(argsi); you can call a regular method by passing actual parameters. can you pass arguments to main? of course, yes. for example, the main metho

57、d in class b is invoked by a method in a, as shown below:43command-line parametersclass testmain public static void main(string args) . java testmain arg0 arg1 arg2 . argn44processingcommand-line parametersin the main method, get the arguments from args0, args1, ., argsn, which corresponds to arg0,

58、arg1, ., argn in the command line.45problem: calculatorfobjective: write a program that will perform binary operations on integers. the program receives three parameters: an operator and two integers. java calculator 2 + 3java calculator 2 - 3 java calculator 2 / 3 java calculator 2 “*” 346regular e

59、xpressionsa regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. regular expression is a powerful tool for string manipulations. you can use regular expressions for matching, replacing, and splitting strings. companion website47matching stringsja

60、va.matches(java);java.equals(java);java is fun.matches(java.*)java is cool.matches(java.*)java is powerful.matches(java.*)companion website48regular expression syntax regular expression matches example x a specified character x java matches java . any single character java matches j.a (ab|cd) a, b,

温馨提示

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

评论

0/150

提交评论