版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
Stringclass/CharacterStringBuffer/FileIntroductiontoAstringisaseriesofcharacterstreatedasasingleConstructingStringnewString=newStringmessage=newString("WelcometoJavaprovidesashorthandinitializerforcreatingaStringmessage="WelcometoString:forstringconstantsStringBuffer/StringBuilder:forstringvariablesIntroductionIntroductiontoJavacharchararray[]={?b?,?i?,?r?,?t?,?h?,??,?d?,?a?,bytebytearray[]={?n?,?e?,?w?,??,?y?,?e?,?a?,?r?};StringBufferbuffer;Strings,s1,s2,s3,s4,s5,s6,s7;publicvoidinit(){s=newString(“hello”);buffer=newStringBuffer();s1=new //anulls2=new //s3=newString(chararray); s4=newString(chararray,6,3); s5=newString(bytearray,0,4,4);//s6=newString(bytearray, //news7=new // StringsAreAStringobjectisimmutable;itscontentscannotbeStrings=s=AfterStrings=
After s=
:StringobjectforIntroductionIntroductiontoJavaStringobjectfors:Stringobjectfors:
Thisstringobjectisnowunreferenced
s:Stringobjectfors1==s1==sisfalses2==sistrues==s3istrueIntroductiontoJavacanonical Strings="WelcometoStrings1=newString("WelcometoJava");Strings2=ern();Strings3="WelcometoSystem.out.println("s1==sis"+(s1==s));System.out.println("s2==sis"+(s2==s));System.out.println("s==s3is"+(s==
::for"Welcometo:AstringobjectforRetrievingIndividualCharactersinapubliccharcharAt(int selectandreturnthecharataspecificposition(index:0..length-1)inthestring“welcometoJava”.charAt(0)(returns
12 WelcometoJaWelcometoJavaStringpublicStringconcat(String s1.concat(s2)concatenatess1ands2asanewobjecttobereturned,ands1ands2arenotIfs2.length==0thenreturntheoriginal==s1+s1+s2+s3+s4+s5sameasmessage.substring(0,message.substring(0,IntroductiontoJavasubstring:enabletocreateanewstringbycopingpartofanexistingobject(s)publicStringsubstring(intbeginIndex,intendIndex):returnasubstringcopyofthecharactersfrombeginIndextoendIndex-1.Strings1="WelcometoStrings2=s1.substring(0,11)+ 12 ComparingStringsLexicographicalcomparison:theintegerUnicodevaluesthatrepresenteachcharacterineachstringarecomparedpublicbooleanequals(Objects1.equals(s2)returnstrueIFs2isastringandhasthesamelengthandthesameUnicodecharactersasthecurrentstring(s1),otherwisereturnsfalse andprimitivedatatypes: bothprimitivedatatypevaluesareidentical/bothreferencesrefertothesameobjectinmemoryComparingStringspublicbooleanequalsIgnoreCase(StringIfthecaseoflettersisignored,twocharacters(c1,c2)areequalonlywhen:(a)c1==c2; publicintcompareTo(String0anegatives1islessthanapositives1isgreaterthanThereturnvalueisthedifferencebetweentheinteger example,h(104)-H(72)=ComparingStringspublicboolean(intstart,Strings2,intostart,int (booleanignCase,intstart,Strings2,intostart,intStringStringstr="Look,booleanb1,b2,b1=str.regionMatches(6,"Look",0, //b2=str.regionMatches(true,6,"Look",0,4);b3=str.regionMatches(true,6,"Look",0,5);publicbooleanstartsWith(Stringprefix,intpublicbooleanstartsWith(StringStringThecontentsofastringcannotbechangedoncethestringiscreated.Butyoucanconvertastringtoanewstringusingthefollowingmethods:FindingaCharacteroraSubstringinaindexOf:searchthefirstoccurrenceofacharacter/substringinastring(s)publicintindexOf(charch,intlastIndexOf:searchthelastoccurrenceofacharacter/substringinastring(s)publicintlastIndexOf(Stringstr,intJava".indexOf('W')returnsJava".indexOf('x')returns-Java".indexOf('o',5)returnsJava".indexOf("come")returnsJava".indexOf("Java",5)returnsJava".indexOf("java",5)returns-"WelcometoJava".lastIndexOf('a')returnsIntroductiontoJavaConversionIntroductiontoJavapublicchar[]s.toCharArray();createsanewcharacterarraycontainingacopyofthecharactersinsExample removeallappearancesofthecharacterinthePublicstaticStringsqueezeOut(Stringfrom,char{char[]chars=from.toCharArray();intlen=chars.length;for(inti=0;i<len;i++) if(chars[i]==toss){System.arraycopy(chars,i+1,chars,i,len--i; returnnewString(chars,0, IntroductiontoJavaConvertCharacterIntroductiontoJavaTheStringclassprovidesseveralstaticvalueOf()methodsforconvertingacharacter,anarrayofcharacters,andnumericvaluestostringsThesemethodshavethesamenamevalueOf()withdifferentargumenttypeschar,char[],double,long,int,andfloatForexample,toconvertadoublevaluetoastring,useString.valueOf(5.44).ThereturnvalueisstringIntroductiontoJavaIntroductiontoJavaObjective:Checkingwhetherastringisapalindrome:astringthatreadsthesameforwardandbackward publicstaticbooleanisPalindrome(String{//Theindexofthefirstcharacterintheintlow=//Theindexofthelastcharacterintheinthigh=s.length()-1;while(low<high){if(s.charAt(low)!=s.charAt(high))returnfalse;//Notapalindromehigh--;}returntrue;//ThestringisapalindromeWrapper
Noclassforbyteand[NumberType]MIN_VALUE,MAX_VALUE[Float,Doble]NEGATIVE_INFINITY,POSITIVE_INFINITYNaN(aninvalidfloatTheCharacter+Character(value:+charValue():+compareTo(anotherCharacter:Character):+equals(anotherCharacter:Character):+isDigit(ch:char):+isLetter(ch:char):+isLetterOrDigit(ch:char):+isLowerCase(ch:char):+isUpperCase(ch:char):+toLowerCase(ch:char):+toUpperCase(ch:char):
ConstructsacharacterobjectwithcharvalueReturnstrueifthischaracterequalstoanotherReturnstrueifthecharacterisanuppercaseletterCharactercharObject=newcharOpareTo(newCharacter('a'))//1charOpareTo(newCharacter('b'))//0charOpareTo(newCharacter('c'))//-1charOpareTo(newCharacter('d')//–2IntroductiontoJavaIntroductiontoJavaObjective:Counteachletterinastringignoringcase-sensitive //InvokethecountLettersmethodtocounteachint[]counts=…/**Counteachletterinthestringpublicstaticint[]countLetters(Strings){int[]counts=newint[26];for(inti=0;i<s.length();{if(Character.isLetter(s.charAt(i)))counts[s.charAt(i)-'a']++;}return}ObjectsoftheStringclass:read-StringBuffer/StringBuilder:modifiable,andusedtoimplement+and+=StringBuffervs.StringBuilderpublicCreateanullstring(theinitialcapacityofcharsispublicStringBuffer(intCreateanullbuffer,wherelengthistheNegativeArraySizeException,IfpublicStringBuffer(StringCreateabuffercontainingthecharactersofstr,andaninitialcapacitywhichisLengthandpublicintThenumberofcharacterscurrentlyinthepublicintThenumberofcharacterscanbestoredinthepublicvoidsetLength(intincrease/decreasethelengthofapublicvoidensureCapacity(intEnsurethecapacitytoaminimumofminCapacityStringBuffersmaybeautomaticallyextendedwhencharactersareappended.ButitisnotsoCapacitymethodsmaybeusedtoavoidextendingbuffersformany10overloadedappendmethods,allowingvariousdatatypevaluestobeaddedtotheendofastringbuffer,example:publicStringBufferappend(doublepublicStringBufferappend(ObjectpublicStringBufferappend(charstr[],intoffset,intpublicStringBufferappend(StringActually,StringBufferandappendareusedbycompilertoimplement+and+=forconcatenating”BC”+22isperformedasIntroductionIntroductiontoJava9overloadedinsertmethods,allowingvariousdatatypevaluestobeinsertedatanypositioninastringpublicStringBufferinsert(intoffset,booleanpublicStringBufferinsert(intoffset,charStringBufferbuf=newStringBuffer();Stringnow=newjava.util.Date().toString();buf.ensureCapacity(buf.length()+now.length()+2);buf.insert(0,now).insert(now.length(),":");IntroductionIntroductiontoJavaPublicstaticStringBufferremove(StringBufferbuf,intpos,intcnt){if(pos<0||cnt<0||pos+cnt>buf.length())thrownewintleftover==buf.length()–(pos+cnt)if(leftover==0){buf.setLength(pos);returnbuf;}char[]chrs=newchar[leftover];buf.getChars(pos+cnt,buf.length(),chrs,0);returnbuf;}IntroductiontoJavaExample:CheckingIntroductiontoJavaObjective:CheckingwhetherastringisapalindromeignoringNon-alphanumericCharacters:astringthatreadsthesameforwardandbackward.Assumethelettersarenotcase-sensitiveP.255-256/**ReturntrueifastringisapalindromepublicstaticbooleanisPalindrome(String{//Createanewstringbyeliminatingnon-alphanumericcharsStrings1=//CreateanewstringthatisthereversalofStrings2=//Compareifthereversalisthesameastheoriginalreturns2.equals(s1);Example:CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyeliminatingnon-alphanumericchars*/publicstaticStringfilter(Strings)//CreateastringStringBufferstrBuf=new//Examineeachcharinthestringtoskipalphanumericcharfor(inti=0;i<s.length();i++)if{strBuf.append(s.charAt(i));}//ReturnanewfilteredreturnstrBuf.toString();CheckingPalindromesIgnoringNon-alphanumeric/**Createanewstringbyreversingaspecifiedstring*/publicstaticStringreverse(Strings){StringBufferstrBuf=newStringBuffer(s);//UsethereversemethodforStringBufferreturn}Command-LineInthemainmethod,gettheargumentsfromargs[0],args[1],...,args[n],whichcorrespondstoarg0,arg1,...,argninthecommandline.classTestMainpublicstaticvoidmain(String[]args) }javaTestMainarg0arg1arg2...Example:javaTestMain“firstnum”aiphaExample:UsingCommand-LineObjective:Writeaprogramthatwillperformbinaryoperationsonintegers.Theprogramreceivesthreeparameters:anoperatorandtwo ifif(args.length!=3)System.out.println("Usage:javaCalculatoroperand1operatoroperand2");javaCalculator2+javaCalculator2-javaCalculator2/javaCalculator2“*”RegularRegularexpressions(regex's)aresetsofsymbolsandsyntacticelementsusedtomatchpatternsoftextRegularexpressionsareanextremelyusefultoolformanipulatingtext,heavilyusedintheautomaticgenerationofWebinthespecificationofprogrammingintext Sincejdk1.4,Javahasaregularexpression Matchermbooleanb,IntroductiontoIntroductiontoJavastaticvoidPatternp=null;//正則表達式Matchermnull操作的字符串booleanb=false;p=Ppile("a*b");m=p.matcher("baaaaab");b=m.matches();p=Ppile("a*b");m=p.matcher("aaaaab");b=m.matches();publicstaticvoidmain(Stringargus[]){test();}
Basic.Matchesanysingle.at=cat,bat,rat,*Matcheszeroormoreoccurrencesofthesingleprecedingcharacter.*at=everythingthatendswithat0*123=123,0123,00123…MatchesanysinglecharacteroftheonescontainedMatchesanysinglecharacterexceptfortheonescontained[cbr]at=cat,bat,[^bc]at=rat,sat…,butnotbat,<[^>]*>=^Beginningof^a=linestartswith$Endof^$=blankline(startswiththeendofline)\Escapesfollowingspecial.\/&[]* \.\\\/\&\[\][cbr]at\.=matchescat.,bat.andrat.only…Charactera,b,orc(simpleAnycharacterexcepta,b,orcathroughz,orAthroughZ,inclusiveathroughd,ormthroughp:[a-dm-p]d,e,orfathroughz,exceptforbandc:[ad-z]athroughz,andnotmthroughp:[a-lq-z]PredefinedCharacter.Anycharacter(mayormaynotmatchlineAdigit:[0-Anon-digit:[^0-Awhitespace [Anon-whitespacecharacter:Awordcharacter:[a-zA-Z_0-Anon-wordcharacter:X,onceornotatX,zeroormoreX,oneormoreX,exactlynX,atleastnX,atleastnbutnotmorethanmtimespattern:xxx-xx-xxxx,xisadigitalregex:[\\d]{3}-[\\d]{2}-[\\d]{4}pattern:(xxx)xxx-xxxx,xisadigital,thefirstnumberisJavapattern:pattern:MonthJune26,RegularExpressionsin021-87888822 IntroductiontoJava IntroductiontoJavaRegularExpressionsinpublicbooleanmatches(StringStringregex="\\w{1,}@\\w{1,}\56\\w{1,}";Stringstr1="zhangsan@";Stringstr2=li@si@;RegularExpressionsinpublicStringreplaceAll(Stringregex,Stringreplacement)publicStringreplaceFirst(Stringregex,Stringreplacement)System.out.println(“JavaSystem.out.println(“JavaJavaJava”,replaceAll(“v\\w”,Output:JawijawiSystem.out.println(“JavaJavaJava”,replaceFirst(“v\\w”,Output:JawiJavaIntroductiontoJavaIntroductiontoJavapublicString[]split(StringpublicString[]split(Stringregex,intlimit)string"boo:and:foo” {"boo","and","foo" {"b","",":and:f"} {"boo","and:foo" {"boo","and","foo" {"boo","and","foo" {"b","",":and:f","","" - {"b","",":and:f","","" {"b","",":and:f"TheFileTheFileclassprovidesseveralcommonmanipulationsthatareusefulwithfilenames.Itprovidesmethodstoseparatepathnamesintosubcomponents,andforqueryingthefilesystemaboutthefileapathnamereferstopublicFile(Stringpath):CreatesaFileobjecttomanipulatethespecifiedpath.ThismethodthrowsaNullPointerExceptionifthepathparameterisnull publicFile(StringdirName,Stringname)File(dirName+File.separator+name) File(fileDir.getPath(),name) Filef1=newFile(“/”);Filef2=newFilef3=new
TheFileget:retrieveinformationaboutcomponentsofaFileobject?sexists:returnstrueifthefileexistsinthefilecanRead:returnstrueifthefileexistsandcanbecanWrite:returnstrueifthefileexistsandcanbeisFile:returnstrueifthefileisanormalisDirectory:returnstrueifthefileisaisAbsolute:returnstrueifthepathisanabsolutepubliclonglastModified():returnsthelastmodificationTheFilepubliclonglength():returnsthefilelengthinpublicbooleanmkdir():Createsadirectory,returningtrueonsuccesspublicbooleanmkdirs():Createsalldirectoriesinthispath,returningtrueifallwerecreatedpublicbooleanrenameTo(Filenew_name):Renamesafile,returningtrueiftherenamesucceededpublicbooleandelete():DeletesthefileordirectorynamedinthisFileobject,returningtrueifthedeletionpublicString[]list():Listsallfilesinadirectoryexcepttheequivalentof“.”and“..”TheFilepublicString[]list(FilenameFilterfilter):Usesthespecifiedfiltertolistfilesinadirectoryequals:trueiftwofileobjectshavethesamepath,notiftheyrefertothesameunderlyingfilesystemobjectFilesarecreatedusingPrintWriter、objectsorRandomAccessFileobjects,notusingFileThecharacterFile.pathSeparatorCharandthestringFile.pathSeparatorrepresentthecharacterthatseparatesfileordirectorynamesinasearchpathimport
IntroductiontoJavapublicIntroductiontoJavapublicstaticvoidmain(Stri
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 勞動合同簽訂前的員工福利制度
- 臨時客服人員聘用合同樣本
- 足球場膜結(jié)構(gòu)施工合同
- 超分子水楊酸換膚治療
- 2022年大學(xué)水利專業(yè)大學(xué)物理下冊期末考試試卷C卷-附解析
- 商業(yè)空地租賃合同范本
- 2022年大學(xué)電氣信息專業(yè)大學(xué)物理二模擬考試試題A卷-含答案
- 餐廳包間地磚鋪設(shè)合同
- IT行業(yè)銷售精英聘用合同
- 通信工程監(jiān)理聘用合同樣本
- T-CBDA 59-2022 家用不銹鋼整體櫥柜應(yīng)用技術(shù)規(guī)程
- 《木雕》課程教學(xué)大綱
- 貧困人口大病專項救治醫(yī)臺帳
- 2022檢驗檢測機構(gòu)全套質(zhì)量手冊及程序文件
- 四年級語文上冊教學(xué)課件-27.扁鵲治病3-部編版(共13張PPT)
- 嗓音(發(fā)聲)障礙評定與治療
- 臨時封路施工方案
- 4kV無功補償技術(shù)規(guī)范
- 減肥與健康PPT
- 新改版教科版六年級下冊科學(xué)全冊知識點歸納 (超全)
- 輸電線路設(shè)計—導(dǎo)線風(fēng)偏計算及校驗實用教案
評論
0/150
提交評論