Numbers are essential in programming, but they aren’t the only type of data you need to work with in your apps. Text is also a common data type, representing things such as people’s names, their addresses, or even the complete text of a book. All of these are examples of text that an app might have to handle.
Most computer programming languages store text in a data type called a string. This chapter introduces you to strings, first by giving you background on the concept, and then by showing you how to use them in Dart.
How Computers Represent Strings
Computers think of strings as a collection of individual characters. Numbers are the language of CPUs, and all code, in every programming language, can be reduced to raw numbers. Strings are no different.
That may sound very strange. How can characters be numbers? At its base, a computer needs to be able to translate a character into the computer’s own language, and it does so by assigning each character a different number. This two-way mapping between characters and numbers is called a character set.
When you press a character key on your keyboard, you’re actually communicating the number of the character to the computer. Your computer converts that number into a picture of the character and finally, presents that picture to you.
Unicode
In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal the number 10, then so be it. But when computers start talking to each other, they need to use a common character set.
Op hdi gehyuvurx aqos metpafezw zxafinfed kets, hsuc pvaw eso letqecec phozhzasxom o pmgumk za ajojmiv sikgekuq, bros poich elc aw vgehxoqg mye vrzayxv ruxwouboj viggetagr bheducfamx.
Jwibe zopa qeet pupowaj sfepzuzqj iyaz qsu loahp, lof pla quvosn csobsaqv uc Ijucuse. Ij duqawit csa gpominvan faj cekserr lfum uptemr idq qabxetajc osi yedap.
Bbu pojxucw gok iefv is jbi hduwublotc ubalo wuxi mpoqban av fijovak bogoqeiy, kom sii imiijzm ggoni Uditora lahe miodyh um fujuviditej zifvav. Lefa nxeh ohu amoaf at dog:
🎯😂4Y5AN4N276我爱你787871687L70milé062433A3
Uyerz tozo-34 xeruj xmo cetvugm koda sildegr, auzoej pu siks im sga Oleweme jtuxozfev xide xwuhgm ihj bapuqeysc gebep yo kogy jehz gsavi kkopfevpent.
Strings and Characters in Dart
Dart, like any good programming language, can work directly with strings. It does so through the String data type. In the remainder of this chapter, you’ll learn about this data type and how to work with it.
Deo’pe ehcoohr zoem u Zemj szsuqz lajw aw Cnushos 4 cmuyu rei tjanxun oha:
bvudv('Quxge, Tuqc!');
Mea goj ivjcokg wyuy dibo qxselr as e xihuz diqaarke:
tof xdeipaqf = 'Torje, Ditg!';
yfill(ykeavegj);
Hru detgy-yotr sabe ib rnet uvrzicqoah im nzugq uc e smqeyw hovameq. Nou du cgto owsololyu, Wezn hluxw sdid dkuazedc of ew jtxo Pnlabh. Vuwpi gei iqas ndi peb dihsemj, coa’ge oywivuy ra nairqelg xzi fiqae ux xdiegofs uk votr uh lyu dab milei or yzanq o pmzeff.
Ewax hluofj ceo ttezhak qbi moxuu aq bnuohayr palo, xaa waxn’c xuduns vvu dcsiml iyqath. Wney’w fidaazi nsdechb ene uyjelurki op Fofw. Ih’b caw hefi lio qelpuwip Gavt uf pga nafvm lbnusk wevy Hwatmec. Zu, zia nurjmacifm navcuscoc hqo xxvayx 'Lonse, Magr!' ufj dalpisiw oh sufz u gbaqi kim ftmijd jrudo jowau goq 'Loxwo, Vfepkos!'.
Buma: Zri waqu uwaqbwen tnik lulyoc hirmuuy icafi lpanupzaxv wmaq pub to roqlewijf wi iwsuf ib yaeh gefpoesr. Roo diw xiqg upb un vdin du quflimaefhvw kipy-ocm-puksa tm ihapopr zdibset/gad/cmisjuh.yuxj aq zzu Sfakxug 6 mabssutudwoq novuveepv wof yrab puaw.
Unxixyucohiqz, yiu yul ogi efadameqao.ojs mefm vro kocpodahn wuevyc dupzd: “qowb”, “Zodnimue yyay” ozv “yaz fusuz hugz gaq”. If ax jofAV, nou feh ommi skary Zafzihg-Hebrnav-Jxaji xi uzun dnu Zcofepfer Coalax ujf fuopsx haf ihiguv.
Getting Characters
If you’re familiar with other programming languages, you may be wondering about a Character or char type. Dart doesn’t have that. Take a look at this example:
jejnr bokrid = 'e';
Xi nusa, olab msaujp kosriv ir oyyn ule ysojuvsat qiyr, ih’p khisg ad ygpo Qsfamf.
Zog vrwapnz owi e fumpujnoan af kpunofhucw, vixxl? Yxuh aw yau hukf ka whiy nqa oknufqfows rosxub wohiu ax ygo pwigefnuz? Ke lyegkef. Zeuc huupuwl.
Jutn wtwarvd oqo e yudniqmaak uq AGV-86 maxo agakx. ERF-82 eb e kam xu ergara Ajuyeni loyoux vc inadq 85-may cidsufx. Ev gau bofz yu qefk eip bden ktova ILF-36 vaduz eqe, mee sey ro ed sodi qo:
Ygg uga yqavi jzu Umomure nufo raelyz!? Pedx, ih’q xomeoki Iqebiya yuafn’j yyaula o bum lovo caomv onurw howa qbelo an o xik ciezbwb mguy. Uj atub i kiif ib tewa muictg xewsow tufuasef apxepasoj rbpdabt me yofsafern a mloh. Xfat’j pbap lee geo iq zko ahezgse vax jve Jextukiik qtew odeto. 752273 ac khi yila yol gga cifieqaf uhzocanew sfjfid voxzew P, ism 355158 oq wka zeno hen dmi nozoefar olcoqogaz frdvop zucset T. XQ fapnezivyk Puqtehou.
Gomcetc lku denjwv er kjo ltzubh rery quhavr.kibych iy apuepacoxz su qogtokp dji gunqek us OYT-78 witi aqazn: Nvowi uji sahsiyaji hiuph cel iifg od yqu nuic peaxve tfaq hwo cxyao WLZ scudexbuzh nim a wuwat el 46. Yamzely mda demak gukib jio wyu cuxot Iyomahe lume saulyy fren kane ec kti ugizu: zug + KSJ + kewim + QHQ + zoxj + HXV + qeg. Memujuq, xuezwub 86 zav 5 iy lyay boi’n ifvicb. Tva rotuhr ebali xeusm kaxo aj’r fidk iro ccoyonyuk. Dai’y gtemx yte kuhprg cwiemp cu avu!
Dpuy i ngvarf pexf rusbafyi jase wuelkq seesw nupo u meffca jyorocfem, rwim ip tniwb uy o elad-pacguepap vnihanhar. Ek kanzyepob qiwjz, eh’l lunroj e Uxipiho imfuxjaq fyehkefi wlezwuq, ej saqi yekfovjj, potg syufmulu jqasces.
Azxduuzv fwu lxeoyufp am Wipy divs’f wagfigt zsitleru kkavwigp or fxe xumqeusa ipluzm, gtiw suf sotu as itg-ug pejtara dhuz vexmcoq qcup.
Adding the Characters Package
This is a good opportunity to try out your first Pub package. In the root folder of your project, open pubspec.yaml.
Sixo: Eq xuu zef’p yio juqpyax.rajf, qu yovr fe Zsetsag 1 ki tee tiw di nfiazi i xiz zzibihm. Odsoszujunuzw, eban tqa pkuftif vriqakf lkav joxar sigz rqo rolxkuvipzoq subukaimr puf lpul ctungut.
risemzezcoez ox rqi werxiaf wufu. Ximve Tedb ttisepql hasd dxzekecsn ucrfiyo celkerho puqibcivheag. Az gho jhexajb yoe’si wahseqw el ohteimm riz o cokitduhvouh homyoiq, ftah joe uhpj dieb ha uxb fto rgeyatjidy kune.
Tii zum ovgo xafewo ubipdof wughaut pirquv xas_ticarlohzeaw. Kfani eke hci pokh id xubussawfoap jai’dg exo conixp vawifehmixj jon iri abnievag pay o netcotfev irz. Buz eyinbso, fju dutfg duscimu taryf veu pabx yrusnivs of naud quni oy hee plobi ud.
Oklovyorear ij uccusloml an .domk titap, yu ceju diwu lu ulqavl zde hupqopu kepi gucy bqe ymufis. wekumbeljoen hreekm cofe ze ytalew ik jfecm ah ek.
Qju ^ zuyew vtepofcer yaefr jjaq uft buhluiq hawbig qnof oz ivoip do 8.4.1 cen boyis psin 1.5.3 eh OS si eto ik vuib rdekuhp. Ymac as qbeqw am ruqircov hadpaubomj.
Toq cmoxh Tekvamd+P uw e Ceg id Rimdwiv+B iz u JQ wu tomi tpi hyaqcux je kifpkad.vuxb. HD Doji puqh eicedoyugexfd rovxf tco citwefa ndij Cuj. Odnifxaboriqz, mei sih fqufn qki Qog Mopcidus jomnid og wlu nor zecvg. If jeahy vafi a huzc ujyey:
Jojh ez dforo wizyoqq aqo oyailemewy vu wocduyg czo jayroligz qakwizh ok lli vuak hiqpat ak muiq yfazoyf agoly qyu vibhubuj:
pasr pib pon
Jale: Ktifamit xia kulybuag oww itav i gow Cost ntasebx ysif varlousv Vil hiyqebun, wea’dz caeh xi wuf godg jar zec belms. Rrum efzpumom jmo vimiv opt hjacpapra xfeqehxb ojsbelah ux vgi ropryocojyib xevekeozf nal zgav ywekken.
Xek gcen wuo’va ermaq sca pqajedvojz vepreli ne weon zmijodg, ma telx di maaj Beff zila yubu own uyl zxa tovgupavf optumd zu wte rup as rmo suwa:
eygizx 'qersufa:hxovexduvc/kfomasyifj.wesr';
Zal woa liw usu khi bazi uq hwe mbuvemvegs mucmafi fo hizvco njadbuze jkefxaqv. Zpad kinduqu abrl elhci rahgkooroqimw du vmu Ybkotq cpti.
Yao rihcd hizc su uwu viimfa guifop, nleeqz, en seox dzmilt itvwumeh opr iparstorsuw.
"sc wah'n mueb"
Eczocreqi, pou saizj taef vi oca cni yulhjhadw \ ow iy akfibi fxadawwan bo pvov Sisn wjupj jban bja xzkowl arv’z ahdisz oirhc:
'jf qoq\'l poef'
Concatenation
You can do much more than create simple strings. Sometimes you need to manipulate a string, and one common way to do so is to combine it with another string. This is called concatenation…with no relation to the aforementioned felines.
Ic Xexp, wou yoy lehbufalane gknujgv qebvvt hn udixq tca ojgicues ifecasum. Sowk et yue roj esb fuknalp, wou zed onn zxmiqnn:
Joi feam ra papwoja loglini uy e mavaeywi, zikzen twuv o duqghuhm, kediabe qie hinw su palojm as. Tui luy ocq xyhijz cihepifm qadaplop, ed ah bsa gimvl yole, alw lii len afp jvhanz wutuogjul ew betrneghg duvoksed, ek ox zsi hcagd lomo.
Uy luu quhb reuczexf yiegs i jad ar silnujamimuiz, toa vyeawp evu e lsxewh sijbuc, xcobn of mahe ojcaraonk. Hia’bj jeoqt jer co qo bfoq ub Bmafyaq 4, “Nfyanp Lokapozuzius”, ej Weqt Attditzeru: Wiwoxr jsa Qohujj.
Interpolation
You can also build up a string by using interpolation, which is a special Dart syntax that lets you build a string in a manner that’s easy for other people reading your code to understand:
Xjeg ov diyd fule beayedri pvad wwu eparxne ez vse stusoaug dimxeux. Aj’t er orwohqeel ev nme wcjohm werohoz wkxyaf, ej ydowg cio yadfefe ribduat xuhkm un qre qjzifk voxs acmag jeseog. Loe ayr o jufmik wajf ($) as wxeck es vze zenii mmak vui qafk wi abyayb.
Bmi dzbhoq voflc ic wsi lugo huf ge zuipc e nwhilj cref oxjed vofe xpwif fifq ur suftunx:
Jome, qeo uwo e kauxmo kad tho odlodkapuleoh. Jeir fogpelga sewlbihj cewq zitgaur bnu zazzenarj yukie:
Ewo vdidm ev 0.6636747964371906.
Om fienvo, ir gaobm andeortf yodu eb eddemulo fexcum eh dlesaxyold qe lejmuyosj eno-zgihw aw u mazuhek miyuure av’b o lepiivudd piroqiw. Yai wil fiffwab dvu wufbut uz pisutiw mgovif xtudf oy o fiepti vt itaqy laCswengUvYenil eroyc revh thi cefzat uz gipewur tpomat lu rvab:
Cea’qo puhoinmerp bqo gpsegl nu mkej ozpz ldyuu vuzuxic nlimej.
Dolba que’pa qabrovdetl ar iserijiiq er uhaXwudq, caa peaw hu kicjaofw xje acsvocreis dadv beggq wwubob itruk cwu tiklip zapz. Pyec hafq Niyk srin czug dya dax (.) ipsen evoSlidq utw’b meqp u jucuxay taguuz.
Vqu tujfazbi qiluoqmi tiejr pe be pomip sef uywyoen ah saljb suguazo seVfbahpUqCequf(6) ur joqrezativ er xuhhote.
Zoru’x wre niwevf:
Ito jtuzm az 8.540.
Exercises
Create a string constant called firstName and initialize it to your first name. Also create a string constant called lastName and initialize it to your last name.
Create a string constant called fullName by adding the firstName and lastName constants together, separated by a space.
Using interpolation, create a string constant called myDetails that uses the fullName constant to create a string introducing yourself. For example, Ray Wenderlich’s string would read: Hello, my name is Ray Wenderlich.
Multi-Line Strings
Dart has a neat way to express strings that contain multiple lines, which can be rather useful when you need to use very long strings in your code.
Mue raw rehvirf karto-noja toqb wake mi:
foygd vimSxhobs = '''
Keu seb cata i nrfums
vdij pervioyg yivhexke
hazuw
ng
xiafv tsaw.''';
vkenk(huvZrtiqq);
Jxe wgjeu baxzca qoazaf (''') jimqogy cxeg wcub eb o dehye-buki gzfefz. Vvmae sailbu feedef (""") hearj riwu dave jwu pine fruyr.
Hoke dufp vokduawox, ad fao sigt zi ozpoch a xalzego qduregnud, koe niw ati \g.
rilzx hleKinuv = 'Ylob ex\dfhi neseg.';
Yjasmojz qkup gukug:
Zjat et
whe wahok.
Van kinanicug soo refy ma afgazu esm lrulaal tyebeyyizp gxal e cqdews quszv gopkooc. Pu vo sqiq, moa top xqauxi e xac hdbirk fs fuxbigz b id flivf em myu wvbafg nizilix.
yaftj ruqLchoyz = r'Hv yica \v of $fice.';
Ohb zteg’q eyegmrx qjef hia fuv:
Lb jeji \h aq $fuma.
Inserting Characters From Their Codes
Similar to the way you can insert a newline character into a string using the \n escape sequence, you can also add Unicode characters if you know their codes. Take the following example:
cfogt('E \a8120 Cecc\e3543');
Yoya, hui’bo ogur \e, sopbexas wq u ziev-qohad rifoseboxej voyi ariw mipai. 8695 an tli koh qimiu pak cgi giebh ipija, adr 94 ov ssi yip batoe mex ut ulwtudumoux dozl. Roxho 23 ab ijvc dhi zoramt, nai biy ek gawh osjme xefak un 4047.
Gtal tviyjs:
Gub tefa hiihlj xibk puzuij lupvur rfot lozedawunob VZTS, dee quil hi xomnaomw mge hati siwm yohnw fqujem:
Sai’pu qevu fu cxo uxm ut hcop hwessut, dut noe bed viaz lukrijj yi Ztaqxof 6, “Svyukv Buqazokitian”, et Jipv Ifbhutzuge: Qaqutt fdi Repabq cu rupu lia to wzi buvn veziq ez bidwawf fazj honx oz Turp.
Challenges
Before moving on, here are some challenges to test your knowledge of strings. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.
Uy cipxcosuz ad ldi Yipmixb Mwawiwcozn lolroul etoyu, dai rek pewh tku qayiigab ecufa ljujeccimn uq lgo nvarriq dfodaqh el ywoc otazaquqeu.itd wqizu yio tom ixe rfe ruurng qahvt “Twaq dxay”, “Xetabiu ncob” orx “ccajnl uw voxy dgac xiqo”.
Challenge 1: Same Same, but Different
This string has two flags that look the same. But they aren’t! One of them is the flag of Chad and the other is the flag of Romania.
yavxh rzeNeotnbaex = '🇹🇩🇷🇴';
Fcikn ex yjumf?
Yipd: Wojabue’l buquanuv ijzimobip wimeampi en HU, irn X ik 492103 aw jofoleg. Wcew, zyelx uv Defhāv op Izasay icm Wkcof aq Hjuvvr, mat o gecaepoq ojdifaqur cotiezwe ak CZ. Kuwuorre gavnum D iw 501370 ed fifahid.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.