Tải bản đầy đủ - 0 (trang)
Chapter 12. Creating and Modifying Text

Chapter 12. Creating and Modifying Text

Tải bản đầy đủ - 0trang

Chapter12.CreatingandModifyingText

12.1 TEXTASUNIMEDIA

12.2 STRINGS:CHARACTERSEQUENCES

12.3 FILES:PLACESTOPUTYOURSTRINGSANDOTHERSTUFF

12.4 OTHERUSEFULCLASSES

12.5 NETWORKS:GETTINGOURTEXTFROMTHEWEB

12.6 USINGTEXTTOSHIFTBETWEENMEDIA

12.7 CONCEPTSSUMMARY



ChapterLearningObjectives

Themedialearninggoalsforthischapterare:

Togenerateaformletter.

Tomanipulatestructuredtext,suchasadelimitedstring.

Towriteprogramsthatreadfromfilesandwritetofiles.

TowriteprogramsthatdirectlyaccessandusetextinformationfromtheInternet.

Towriteaprogramthatmodifiesanotherprogram.

Togeneraterandomlystructuredtext.



Tousetexttochangeencodingsofinformation,e.g.,creatingvisualizationsof

sounds.

Thecomputersciencegoalsforthischapterare:

Tomanipulatestrings.

Toreadandwritefiles.

Tohandleexceptions.

Touseadynamicarray:ArrayList.

Toexplaininterfaces.

Toworkwithfilestructures.

Towriteprogramsthatmanipulateprograms,whichleadstopowerfulideaslike

interpretersandcompilers.

Touseclassesinpackagesthatyouhavetoimport.

Toiteratewithawhileloop.

ToaccesstheInternetviaaprogram.







[Page387]



12.1.TextasUnimedia

NicholasNegroponte,founderoftheMITMediaLab,saidthat

whatmakescomputer-basedmultimediapossibleisthefact

thatthecomputerisactuallyunimedia.Thecomputerreally

onlyunderstandsonething:zerosandones.Wecanusethe

computerformultimediabecauseanymediumcanbeencoded

inthesezerosandones.

Buthemightaswellhavebeentalkingabouttextasthe

unimedia.Wecanencodeanymediumastext,andwhat'seven

betterthanthezerosandones,wecanreadthetext!Laterin

thischapter,wemapsoundstotextandthenbacktosounds.

Butoncewe'reintext,wedon'thavetogobacktotheoriginal

medium:Wecanmapsoundstotextandthentopictures,and

thuscreatevisualizationsofsounds.

TheWorldWideWebisprimarilytext.VisitanyWebpage,then

gotothemenuofyourWebbrowserandchoose"Viewthe

source."Whatyouwillseeistext.EveryWebpageisactually

text.Thattextreferencespictures,sounds,andanimationsthat

appearwhenyouviewthepage,butthepageitselfisdefined

astext.Thewordsinthattextareinanotationcalled

HyperTextMarkupLanguage(HTML).



[Page387(continued)]



12.2.Strings:CharacterSequences

Textistypicallymanipulatedasstrings.InJavaastringisa

sequenceofcharacters.StringsinJavaarenotjustarraysof

charactersastheyareinsomeotherlanguages,likeC.Strings

areobjectsoftheStringclass.

Youuseadoublequotetoindicatethestartandendofastring

inJava.IfyouwanttowriteaJavaprogramthatcreatesHTML

pages,youwillneedstringsthatcontainquotes.Ifyouwant

thestringtoincludeadoublequote,youmustuseabackslash

'\'infrontofit.

>System.out.println("Hesaid,\"Hi.\"");

Hesaid,"Hi."



Youcanincludesinglequotesinstrings.

>System.out.println("Hewon'tgoout!");

Hewon'tgoout!



Astringcontainsasequenceofcharacters.Wecanthinkabout

thecharactersofthestringasbeinginboxes,eachwithitsown

indexnumber.Youcangetacharacterfromastringusingthe

methodcharAt(index).



>Stringhello="Hello";

>System.out.println(hello.charAt(0));

H

>System.out.println(hello.charAt(2));

l



[Page388]

Youcanuseaforlooptowalkthroughallthecharactersofa

string.

>Stringtest="Hello";

>for(inti=0;i
System.out.println(test.charAt(i));

H

e

l

l

o



Noticethatyoudoneedtheparenthesesafterlength().Itisa

methodoftheStringclass,notapublicfieldasitisforanarray.



12.2.1.Unicode

JavausesUnicodetoencodeeachcharacter.Unicodeisan

encodingforcharacterswheretwobytesareusedforeach

character.Twobytesgivesus65,536possiblecombinations.

Havingthatmanypossiblecombinationsallowsustogobeyond

asimpleLatinalphabet,numbers,andpunctuation.Wecan

representHiragana,Katakana,andotherglyph(graphical



depictionsofcharacters)systems.

Whatthisshouldtellyouisthattherearemanymorepossible

charactersthancanbetypedatastandardkeyboard.Notonly

aretherespecialsymbols,butthereareinvisiblecharacterslike

tabsandbackspace.WespecifytheseinJavastrings(andin

manyotherlanguages,suchasC)usingbackslashescapes.

Backslashescapesarethebackslashkey\followedbya

character.

\"allowsforadoublequoteinsideofastring.

\tisthesameastypingthetabkey.

\bisthesameastypingthebackspacekey(whichisnota



particularlyusefulcharactertoputinastring,butyoucan).

Whenyouprint\b,itshowsupasaboxonmostsystemsit's

notactuallyprintable.

\nisthesameastypingtheenter/returnkey.Itisoften



calledthenew-linecharacter.

\uXXXXwhereXXXXisacodemadeupof0-9andA-F(known



asahexadecimalnumber)representstheUnicodecharacter

withthatcode.Youcanlookupthecodesat

http://www.unicode.org/charts.

Herearesomestringswithspecialcharactersinthem.Tryouta

stringwithabackspaceinitforyourself.



>System.out.println("Astringwithatab\tinit");

Astringwithatabinit

>System.out.println("Astringwithanewlinecharacter\nini

Astringwithanewlinecharacter

init



[Page389]



12.2.2.StringMethods

TheStringclasshasmanymethodsforworkingwithString

objects.Thesemethodsareusefulforprocessingtext.

charAt(intposition)returnsthecharacteratthegivenposition



inthestring.Thefirstcharacterisatposition0,justasthe

firstelementofanarrayisatindex0.

>Stringstr1="Bye";

>System.out.println(str1.charAt(0));

B

compareTo(Objecto)returnsanegativenumberifthisobjectis



lessthanthepassedobject,0ifthisobjectisequaltothe

passedobjectandapositivenumberifthisobjectisgreater

thanthepassedobject.

>Stringstr1="Bye";

>Stringstr2="Hi";

>Stringstr3=newString("Bye");

>System.out.println(str1.compareTo(str2));

-6

>System.out.println(str2.compareTo(str1));

6

>System.out.println(str1.compareTo(str3));

0

substring(intn,intm)returnsanewstringwhichisa



substringofthestringstartingatthenthcharacterand



precedinguptobutnotincludingthemthcharacter.A

substringincludespartoftheoriginalstring.

>Stringstr2="Doyougotoschool?";

>Stringstr3=str2.substring(3,6);

>System.out.println(str3);

you

substring(intn)returnsanewstringwhichisasubstringof



thestringstartingatthenthcharacterandincludingthe

restofthecharactersinthestring.

>str3=str2.substring(6);

>System.out.println(str3);

gotoschool?

startsWith(Stringprefix)returnstrueifthestringstartswith



thegivenprefix,elseitwillreturnfalse.

>Stringletter="Mr.Guzdialrequeststhe";

>letter=letter+"pleasureofyourcompany...";

>System.out.println(letter.startsWith("Mr."));

true

>System.out.println(letter.startsWith("Mrs."));

false

endsWith(Stringsuffix)returnstrueifthestringendswiththe



givensuffix,elseitwillreturnfalse.



[Page390]

>Stringfilename="barbara.jpg";

>if(filename.endsWith(".jpg"))

System.out.println("itisapicture");

itisapicture

indexOf(Stringstr)returnsthefirstindexofthepassedstr,if



itisfound.Ifstrisn'tinthecurrentstring,itwillreturn1.

>System.out.println(letter);

Mr.Guzdialrequeststhepleasureofyourcompany...

>System.out.println(letter.indexOf("Guzdial"));

4

>System.out.println(letter.indexOf("Mark"));

-1

indexOf(Stringstr,intfromIndex)returnsthefirstindexofthe



passedstratorafterthepassedfromIndex,ifitisfound.If

strisn'tinthecurrentstringatorafterthefromIndex,itwill

return1.



>Stringt="Thatwhichis,is.Thatwhichisnot,isnot.";

>System.out.println(t.indexOf("is",14));

15

lastIndexOf(Stringstr)returnsthelastindexofthepassed

str,ifitisfound.Ifstrisn'tinthecurrentstring,itwill



return1.

>Strings="Itisaniceday,isn'tit?";

>System.out.println(s.lastIndexOf("it"));

24

lastIndexOf(Stringstr,intindex)returnsthelastindexofthe



passedstrfoundlookingbackwardstartingatindex.Ifstr

isn'tinthecurrentstringbeforethegivenindex,itwill

return1.

>Strings="Itisaniceday,isn'tit?";

>System.out.println(s.lastIndexOf("is",17));

3

toUpperCase()returnsanewstringwithallthecharactersin



uppercase.



>System.out.println("Hello".toUpperCase());

HELLO

toLowerCase()returnsanewstringwithallthecharactersin



lowercase.

>System.out.println("Hello".toLowerCase());

hello

replace(StringoldStr,StringnewStr)returnsanewstringwith



thecharactersintheoldStrreplacedwiththecharactersin

thenewStrforalloccurrencesoftheoldStr.Thisisnewin

Java1.5.

>System.out.println(letter);

Mr.Guzdialrequeststhepleasureofyourcompany...

>System.out.println(letter.replace("a","!"));

Mr.Guzdi!lrequeststheple!sureofyourcomp!ny...



[Page391]

replaceAll(Stringregex,StingnewStr)thiswillreturnanew



stringwithallthematchingsubstringsspecifiedbythe

regularexpression(regex)replacedwiththecharactersin

newStr.Aregularexpressioncanbejustastringof

characters,oritcanalsousespecialcharacterstoindicate

thatitwillmatchanycharacter,anydigit,onlyuppercase

characters,andsoon.Ifyouuseitwithastringof

characters,itisthesameasthereplacemethod.

>System.out.println(letter);

Mr.Guzdialrequeststhepleasureofyourcompany...

>System.out.println(letter.replaceAll("a","!"));

Mr.Guzdi!lrequeststheple!sureofyourcomp!ny...

Toreplacealldigits(09)withaspace,do:



>Stringtest="This9isatest7";

>System.out.println(test.replaceAll("\\d",""));

Thisisatest

Toremoveallnon-digits,do:

>Stringinput="7a8c";

>System.out.println(input.replaceAll("\\D",""));

78

replaceFirst(Stringregex,StingnewStr)thiswillreturnanew



stringwiththefirstsubstringthatmatchestheregular

expressionspecifiedbyregexreplacedwiththecharactersin

newStr.Aregularexpressioncanbejustastringof

charactersoritcanalsousespecialcharacterstoindicate

thatitwillmatchanycharacter,anydigit,onlyuppercase

characters,andsoon.

>System.out.println(letter);

Mr.Guzdialrequeststhepleasureofyourcompany...

>System.out.println(letter.replaceFirst("a","!"));

Mr.Guzdi!lrequeststhepleasureofyourcompany...

split(Stringregex)thiswillreturnanarrayofStringobjects.It



willsplitthecurrentstringintomanystringsbybreakingit

whereveritmatchestheregularexpressionspecifiedin

regex.

>System.out.println(letter);

Mr.Guzdialrequeststhepleasureofyourcompany...

>String[]strArray=letter.split("");

>for(inti=0;i
System.out.println(strArray[i]);

Mr.

Guzdial

requests

the



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Creating and Modifying Text

Tải bản đầy đủ ngay(0 tr)

×