版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter9StringsandTextI/O1MotivationsOftenyouencountertheproblemsthatinvolvestringprocessingandandoutput.Supposeyouneedtowriteaprogramtoreplacealloccurrencesofawordwithanewwordinafile.Howdoyousolvethisproblem?Thischapterintroducesstringsandtextfiles,whichwillenableyoutosolvethisproblem.2ObjectivesTousetheStringclasstoprocessfixedstrings(§9.2).TousetheCharacterclasstoprocessasinglecharacter(§9.3).TousetheStringBuilder/StringBufferclasstoprocessflexiblestrings(§9.4).TodistinguishamongtheString,StringBuilder,andStringBufferclasses(§9.2-9.4).Tolearnhowtopassargumentstothemainmethodfromthecommandline(§9.5).TodiscoverandtodeleteandrenamefilesusingtheFileclass(§9.6).TowritedatatoathePrintWriterclass(§9.7.1).ToreaddatafromatheScannerclass(§9.7.2).(GUI)Toopenfilesusingadialogbox(§9.8).3TheStringClassConstructingaString:Stringmessage="WelcometoJava“;Stringmessage=newString("WelcometoJava“);Strings=newString();ObtainingStringlengthandRetrievingIndividualCharactersinastringStringConcatenation(concat)Substrings(substring(index),substring(start,end))Comparisons(equals,compareTo)StringConversionsFindingaCharacteroraSubstringinaStringConversionsbetweenStringsandArraysConvertingCharactersandNumericValuestoStrings4ConstructingStringsStringnewString=newString(stringLiteral);
Stringmessage=newString("WelcometoJava");Sincestringsareusedfrequently,Javaprovidesashorthandinitializerforcreatingastring:Stringmessage="WelcometoJava";5StringsAreImmutableAStringobjectisimmutable;itscontentscannotbechanged.Doesthefollowingcodechangethecontentsofthestring?Strings="Java";s="HTML";6TraceCode
Strings="Java";s="HTML";animation7TraceCode
Strings="Java";s="HTML";animation8InternedStringsSincestringsareimmutableandarefrequentlyused,toimproveefficiencyandsavememory,theJVMusesauniqueinstanceforstringliteralswiththesamecharactersequence.Suchaninstanceiscalledinterned.Forexample,thefollowingstatements:9Examplesdisplay
s1==sisfalses1==s3istrueAnewobjectiscreatedifyouusethenewoperator.Ifyouusethestringinitializer,nonewobjectiscreatediftheinternedobjectisalreadycreated.10TraceCodeanimation11TraceCode12TraceCode13StringComparisons14StringComparisonsequals Strings1=newString("Welcome“); Strings2="welcome";
if(s1.equals(s2)){//s1ands2havethesamecontents
}
if(s1==s2){//s1ands2havethesamereference
}15StringComparisons,cont.compareTo(Objectobject) Strings1=newString("Welcome“); Strings2="welcome";
if(pareTo(s2)>0){//s1isgreaterthans2}elseif(pareTo(s2)==0){//s1ands2havethesamecontents}else//s1islessthans216StringLength,Characters,andCombiningStrings17FindingStringLengthFindingstringlengthusingthelength()method:message="Welcome";message.length()(returns7)18RetrievingIndividualCharactersinaStringDonotusemessage[0]Usemessage.charAt(index)Indexstartsfrom019StringConcatenationStrings3=s1.concat(s2);Strings3=s1+s2;s1+s2+s3+s4+s5sameas(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);20ExtractingSubstrings21ExtractingSubstringsYoucanextractasinglecharacterfromastringusingthecharAtmethod.YoucanalsoextractasubstringfromastringusingthesubstringmethodintheStringclass.Strings1="WelcometoJava";Strings2=s1.substring(0,11)+"HTML";22Converting,Replacing,andSplittingStrings23Examples"Welcome".toLowerCase()returnsanewstring,welcome."Welcome".toUpperCase()returnsanewstring,WELCOME."Welcome".trim()returnsanewstring,Welcome."Welcome".replace('e','A')returnsanewstring,WAlcomA."Welcome".replaceFirst("e","AB")returnsanewstring,WABlcome."Welcome".replace("e","AB")returnsanewstring,WABlcomAB."Welcome".replace("el","AB")returnsanewstring,WABlcome.24SplittingaStringString[]tokens="Java#HTML#Perl".split("#",0);for(inti=0;i<tokens.length;i++)System.out.print(tokens[i]+"");JavaHTMLPerldisplays25Matching,ReplacingandSplittingbyPatterns
Youcanmatch,replace,orsplitastringbyspecifyingapattern.Thisisanextremelyusefulandpowerfulfeature,commonlyknownasregularexpression.Regularexpressioniscomplextobeginningstudents.Forthisreason,twosimplepatternsareusedinthissection.PleaserefertoSupplementIII.F,“RegularExpressions,”forfurtherstudies.
"Java".matches("Java");"Java".equals("Java");"Javaisfun".matches("Java.*");"Javaiscool".matches("Java.*");26Matching,ReplacingandSplittingbyPatterns
ThereplaceAll,replaceFirst,andsplitmethodscanbeusedwitharegularexpression.Forexample,thefollowingstatementreturnsanewstringthatreplaces$,+,or#in"a+b$#c"bythestringNNN.Strings="a+b$#c".replaceAll("[$+#]","NNN");System.out.println(s);Heretheregularexpression[$+#]specifiesapatternthatmatches$,+,or#.So,theoutputisaNNNbNNNNNNc.
27Matching,ReplacingandSplittingbyPatterns
Thefollowingstatementsplitsthestringintoanarrayofstringsdelimitedbysomepunctuationmarks.String[]tokens="Java,C?C#,C++".split("[.,:;?]");
for(inti=0;i<tokens.length;i++)System.out.println(tokens[i]);28FindingaCharacteroraSubstringinaString29FindingaCharacteroraSubstringinaString"WelcometoJava".indexOf('W')
returns0."WelcometoJava".indexOf('x')
returns-1."WelcometoJava".indexOf('o',5)
returns9."WelcometoJava".indexOf("come")
returns3."WelcometoJava".indexOf("Java",5)
returns11."WelcometoJava".indexOf("java",5)
returns-1."WelcometoJava".lastIndexOf('a')
returns14.
30ConvertCharacterandNumberstoStringsTheStringclassprovidesseveralstaticvalueOfmethodsforconvertingacharacter,anarrayofcharacters,andnumericvaluestostrings.ThesemethodshavethesamenamevalueOfwithdifferentargumenttypeschar,char[],double,long,int,andfloat.Forexample,toconvertadoublevaluetoastring,useString.valueOf(5.44).Thereturnvalueisstringconsistsofcharacters‘5’,‘.’,‘4’,and‘4’.31Problem:FindingPalindromesObjective:Checkingwhetherastringisapalindrome:astringthatreadsthesameforwardandbackward.CheckPalindromeRun32TheCharacterClass33ExamplesCharactercharObject=newCharacter('b');charOpareTo(newCharacter('a'))returns1charOpareTo(newCharacter('b'))returns0charOpareTo(newCharacter('c'))returns-1charOpareTo(newCharacter('d')returns–2charObject.equals(newCharacter('b'))returnstruecharObject.equals(newCharacter('d'))returnsfalse34Problem:CountingEachLetterinaStringThisexamplegivesaprogramthatcountsthenumberofoccurrenceofeachletterinastring.Assumethelettersarenotcase-sensitive.
CountEachLetterRun35StringBuilderandStringBufferTheStringBuilder/StringBufferclassisanalternativetotheStringclass.Ingeneral,aStringBuilder/StringBuffercanbeusedwhereverastringisused.StringBuilder/StringBufferismoreflexiblethanString.Youcanadd,insert,orappendnewcontentsintoastringbuffer,whereasthevalueofaStringobjectisfixedoncethestringiscreated.36StringBuilderConstructors37ModifyingStringsintheBuilder38ExamplesstringBuilder.append("Java");stringBuilder.insert(11,"HTMLand");stringBuilder.delete(8,11)changesthebuildertoWelcomeJava.stringBuilder.deleteCharAt(8)changesthebuildertoWelcomeoJava.stringBuilder.reverse()changesthebuildertoavaJotemocleW.stringBuilder.replace(11,15,"HTML")changesthebuildertoWelcometoHTML.stringBuilder.setCharAt(0,'w')setsthebuildertowelcometoJava.39ThetoString,capacity,length,setLength,andcharAtMethods40Problem:CheckingPalindromesIgnoringNon-alphanumericCharactersThisexamplegivesaprogramthatcountsthenumberofoccurrenceofeachletterinastring.Assumethelettersarenotcase-sensitive.PalindromeIgnoreNonAlphanumericRun41MainMethodIsJustaRegularMethodYoucancallaregularmethodbypassingactualparameters.Canyoupassargumentstomain?Ofcourse,yes.Forexample,themainmethodinclassBisinvokedbyamethodinA,asshownbelow:42Command-LineParametersclassTestMain{ publicstaticvoidmain(String[]args){...}}javaTestMainarg0arg1arg2...argn43Processing
Command-LineParametersInthemainmethod,gettheargumentsfromargs[0],args[1],...,args[n],whichcorrespondstoarg0,arg1,...,argninthecommandline.44Problem:CalculatorObjective:Writeaprogramthatwillperformbinaryoperationsonintegers.Theprogramreceivesthreeparameters:anoperatorandtwointegers.
CalculatorjavaCalculator2+3javaCalculator2-3RunjavaCalculator2/3javaCalculator2“*”345RegularExpressionsAregularexpression(abbreviatedregex)isastringthatdescribesapatternformatchingasetofstrings.Regularexpressionisapowerfultoolforstringmanipulations.Youcanuseregularexpressionsformatching,replacing,andsplittingstrings.CompanionWebsite46MatchingStrings"Java".matches("Java");"Java".equals("Java");"Javaisfun".matches("Java.*")"Javaiscool".matches("Java.*")"Javaispowerful".matches("Java.*")CompanionWebsite47RegularExpressionSyntaxCompanionWebsite48ReplacingandSplittingStringsCompanionWebsite49ExamplesStrings="JavaJavaJava".replaceAll("v\\w","wi");Strings="JavaJavaJava".replaceFirst("v\\w","wi");String[]s="Java1HTML2Perl".split("\\d");CompanionWebsite50TheTheFileclassisintendedtoprovideanabstractionthatdealswithmostofthemachine-dependentcomplexitiesoffilesandpathnamesinamachine-independentfashion.Theisastring.TheFileclassisawrapperclassfortheanditsdirectorypath.51Obtainingandmanipulatingfile52Problem:ExploreTestRunObjective:Writeaprogramthatdemonstrateshowtocreatefilesinap
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 印刷材料的科技创新与应用考核试卷
- 2025年医疗病例管理协议
- 2025年度美发店客户满意度调查与服务提升合同8篇
- 2025年食堂档口租赁及市场营销合作合同范本3篇
- 2024门店超市经营管理承包合同3篇
- 2025年度绿色建材采购与施工一体化项目承包合同4篇
- 2025年度智能家用空调安装与维护服务协议书
- 2025年度模具制造设备租赁及节能改造合同4篇
- 二零二五年度版黄金首饰等抵押交易合同
- 2025年度绿色有机粮食购销合作经营协议
- 电缆挤塑操作手册
- 浙江宁波鄞州区市级名校2025届中考生物全真模拟试卷含解析
- IATF16949基础知识培训教材
- 【MOOC】大学生创新创业知能训练与指导-西北农林科技大学 中国大学慕课MOOC答案
- 劳务派遣公司员工考核方案
- 基础生态学-7种内种间关系
- 2024年光伏农田出租合同范本
- 《阻燃材料与技术》课件 第3讲 阻燃基本理论
- 2024-2030年中国黄鳝市市场供需现状与营销渠道分析报告
- 新人教版九年级化学第三单元复习课件
- 江苏省南京鼓楼区2024年中考联考英语试题含答案
评论
0/150
提交评论