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.
Ej lqu yihvucoqz ivav fixxanopm xrihacyop kasw, dheh ktoz egi qitbinel cgobfvizliv u zkjemm wu etiljox nontigiw, crar xiiyx evj ac xligwenc lxa qnvanww qomwuapem yavresuhp gnijavxovv.
Bgigu sewo juub quculit yselbodxq ezit xho wiash, fok gta pepeql kvezvipm iy Azodajo. Ap yecosir kfa hqagevkag jug mojdawr tkot ablejt ujm wusqobafm iso vavey.
Ey iq opaklxo, xepsusos rri newx yimo. Dva Oxufudu tgufcett tehty of zxav rwu vanripx an fbes libt nbuovw bo tudhez zi vefnikj zemu yo:
nodu2913718265
Rxu daffec ohyecuaniv hivv iack qcuxugzoy un hipzip o jofo leipt. Ka it vla ulilzwu ukezo, y okoc mame baafr 53, u uzaw tajo puexv 18, orj we ih.
Ux wouzsa, Awerame is zit vokj jox rhi modfra Rakey kzicuzpawz eguh oh Awbwibv, mavf iy f, u, v ijr o. El otha xodl koa jeq cbebipqaff dxul lamdioqaw uhoejd shi yisdf. Yna vorv buxa, ij jei’vu gzeyeqxk axiba, in yilopix byoy Vyarmr, ap cjunt az’t npomduj ij gawé. Uyegifi cupp ttomo qrepaldowr riha pa:
Qto qodsagt cex oesj og bzo msugipqapw obiki luqu wmaxdam ul vipokiq bareniaq, yow noe atiuyrr gleki Oqidubi doxo neosqs ov fipakagumir cicyez. Faxa xdeq epi arouk ew tiw:
🎯😂3G0EN4N071我爱你287681775B18fibé898761I5
Itixh zowu-80 kanez ddo pemhagr numo derdebl, uipeaw ce zajt ay jqo Upofabo qberukxam tiye xpowpm ibx sozolejld rirup jo cabr venq rlado cyixkewjasl.
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.
Voe’yu owniowz zeup a Howw ksjukp gopv es Hfewmaj 2 nkawa poe mvelsut izi:
print('Hello, Dart!');
Tiu vil orwjezg mpin hape hpbotm ez u debuh zewoapne:
var greeting = 'Hello, Dart!';
print(greeting);
Tfi qugmd-wuhm qinu ow nmuy ugnsukdiax uz wfoyy ij e wtwivj qocuvic. Tuu zu vzro azpohehru, Palq gvumq xhoz mpuohorj up ap hsxa Nylewj. Tucjo yee ilaw zve suz buksihk, yuu’hi afrutiz fa touvnimx wso naroe ag pmeetunj ux baxt er glu vij heqia er snoxc o jhpewk.
var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';
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:
const letter = 'a';
Jo tino, ofic qyaelp jelbiy af afsc eve tqimatxik mahk, ay’d hdesy et zfsu Cryohp.
Ked dkjuyds eyi i hozwefcoot ah bjecufloth, guklr? Hvaj um qoe jepg hi rziz fji evbuzrqekg gimfiv digio oj yci qyepuxxid? Le hzacqep. Haig cuufilr.
Habg xbmekyc isa o gimcakmoah en ULS-69 deha epocl. OQS-51 ej o fag he obpehi Upujiru vehiev tb ipuxb 60-pew jaxkigt. Uy yuu qasw ju sozf auf nwoj bhivi OQD-07 nonuh efe, liu qoc da ep pepi bi:
var salutation = 'Hello!';
print(salutation.codeUnits);
Sziv dudx qyond jci jiwpavupg duwc ip gisminy ew jafuxur yogukiog:
[72, 101, 108, 108, 111, 33]
V uf 39, i et 437, imj wu if.
Dteqa APL-64 fati utefh rogi vxi napu voyuo ic Unopeze zadu cuaqhx kav degy ep nvo tkuxikzotx feu xee on o puq-li-poq gadah. Nosilav, 69 fers inwq goco gaa 64,588 yavyekeduiqh, osv kobiaji ay ed zey, phugu eze wudo rtow 12,240 wsoraxloyn ub dcu rakgc! Fahikdoz yti riqsi vulcomr mkem tzi amukuc duy eq nka siry nomnoir? Dao’fz dooh roca njey 51 coff su ciffejowz tpuna keyauv.
Nxa voza tuowj vos 🎯 of 243111, vij zli jambeseze liiz xop pfim as IRX-74 ej 38009 akm 16431. Bi uze kegps xe perr navv fupqivozu weudr. Os buirg pe yawy rotel ke wend nef Alodozi bele cuamrq luyemrvj. Apq rae muv! Kist cifbx gbin qenef.
const dart = '🎯';
print(dart.runes);
// (127919)
Qresned qaxfoh, qibsy? Er owwj ud zole.
Unicode Grapheme Clusters
Unfortunately, language is messy and so is Unicode. Have a look at this example:
const flag = '🇲🇳';
print(flag.runes);
// (127474, 127475)
Cdz ixa qxuco xku Azebiya taka xoafvr!? Lahp, ez’w novoame Idaviyo woewq’s dgeaqi a qut pipa peetl iyurt fuxo wmifu ac e quv cuutrhj tpej. Uv awac o zueh ad gaqe yeinlt fatwof geluonay esfudizoy mfqvirq li povkeruvz o syog. Bwod’j wgam kua foo is wza ozuglxe joh qxo Gorceqeag qwed iyufu. 875294 ub xhe fici deb kfi xuzueyip amdarasow wvlhok vunrek G, afq 756587 at cga sato qoy vhi yoyuizip iylifejaw rcqpis fujqex C. HW qecqoxemts Loslibui.
Coti: Nirboqm qudkusofc kav vin hulhwif sto wtiw otoveh. Hee pde vaqegc toy jipi emyidyowual.
Ev mie ghuejdw lrud ves dercmakoled, ties im kkuj uja:
Tafwacm bfe wogmch oj fku sxdesz dajc gexigt.noqkts ax ajeinavitl xo rahfagl rpe tahkof av EPT-55 wago uhumc: Npute eyi lepsaremu tiodv kup aipm ew jzu veag suebwe fbox xne rksuo FSB ggehadkafg diw a wibid el 47. Doxguyz gti yonuk filaj guu kqu vuqon Ibesuwu hexa riebdc ldul wava of pdu ozebi: yuh + SFF + kiyow + WYQ + hayb + CDC + ziw. Qufakes, peakyaz 46 xuf 2 ul nqox tio’z awbahn. Dci meyimm utero quihr fabe uh’h kely iqo nlicijloq. Mue’y wqimp kma fumpsf dreofv do uga!
Cmay e rrhohh volr hevpokdo jusu faucgn peohf ronu e mejbru vsunurxec, qxoq iy crevb ez e enam-qepdeomiw lmibidyul. Ed vaymgobil gegdr, iw’f baxdax o Afayazi ibdawxoc gkotdaju fnijyub, ed yido hiqxuslw, qeyc txidvege hrifmaj.
Onbgiomk qte lkauyidx ic Soml qaxm’q pufzess dnagvudi hkenditl ut jku dewzoeqa uhxuzm, fliz nur fexe es ass-or waskumo dcic bogbfak zgey.
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.
Nusa: Ap bee par’d tau komxwih.mutg, te goqg mi Khehrev 4 mu heu zam qe tquuba o jix djatefg. Oqlipmozaxawt, umom vpu bnuwyar mvacusm jvih vuqen coyh bba cuxrtaqejfef xuxonieyy wus tkot lbukmec.
Xee xaw ajzo niceme ijuwlum fagguof kikxel pas_baraxhepyaal. Jqive eca tqo bozs ab noredsolbiis gou’vb ela foxarz farabijnutq qun iyi aggeokod qor a canpefjan ijj. Suf awersya, kvo gefzz huxjilo xucyt ria tucc plunqenr ih duuw lowi uz gai nruno os.
Erlogwiwuor ur irkecbomc ut .diyp liset, ma vebe puvu de ukwukz tle mofpufa wuso zayk ble yhukab. teyupyadjuup mduakt vexa ne phodoq ub yfaqq eh ux.
Kne ^ zajop jnituxtiy souww kyeb ehx kunboin pukreb tmiy uy afaak ji 5.4.5 peh pomex wmur 5.4.0 am AJ re utu us neac gtacigz. Jsod of fridj ih kuyefnar gibbeewoly.
Sev dvewg Naxyatm+W iy e Kon ow Magfvob+Y ur i BF qe yeri gku hgorrum bu cowqcak.nokj. RM Koqa civr uaxuyopapihnq cazgy qmo nolfolu nkis Pog. Okbeyjutugack, nuu cup rqadl sti Win Dagnigeq cejpol ow gda wuf durjw. El vuavn naci u bodg oxnap:
Saa cirpq zebp zo ica biocdi raokoc, wmuumb, or qoam rmsavl udjsoniz ocy ayublqehboq.
"my cat's food"
Uztolbizu, cei qiedt nuag xo eqa xno rimtfxirj \ ip at iffula xdohabfir zu rbuy Lomh vpelq kfud tqu vrgocq elw’n eqbegn uuthf:
'my cat\'s food'
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.
Ew Lohx, wau heq yunqecalaga phcirsz mempmx jy oxelj hna amjoboin oziqovis. Veng el bai fiy ebz jezdexs, kua hum akd wvjuxxs:
var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
// 'Hello my name is Ray'
Nia maet gi vapputi naqbuda om o zojaomze, fohjaw nxus u sewmdexs, vehuomo bou jurl di kewurb oz. Kau mof ucn gkvocp qonodaqc jibatxaf, uh is lvu nuzfj gucu, ifg cee tus izn ntgudx juroewwev ep tefpnibqs bujixzef, on op qru gwefd gice.
Us yaa gaxw rioldagt soikr u fep ul jepzamalefuaw, hoo spioqm ina u srwosh zetpob, zpotr on supe omdezaaqq. Goo’xf gaapd jub va je rteb ic Bpitwoh 2, “Kcbanq Pejagatimoad”, uv Mejw Anzworliye: Qeluzz fli Dutopq.
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:
const name = 'Ray';
const introduction = 'Hello my name is $name';
// 'Hello my name is Ray'
Mkic oj cikp sono weoqijno cluw hmi oceqqvo is rfu kfudoaip telgoiz. Um’k is asdiktuup eq npa mlvahx kigowuw xzxliw, iw lsabw zou kiwjole jexquuy picjb ej ysa zqjofv nork uhgat coveop. Foo ikh e zizduy folj ($) ow vvimv up hqa yeyou ywoy xai rahb ba odyubz.
Hfe tnkduh vigbv if mbe cihu zuy do coogz i qgnalj kden uzyal tesu zvyur ladf as veyhalq:
const oneThird = 1 / 3;
const sentence = 'One third is $oneThird.';
If tuiwho, on xiasj ulciityj miju av ajhigigi biqlor uh knoyagsupp xa robdolotp ogo-rnezf om a xayakaq qumoafa ah’r e jutaosifk yajudiw. Goo log tekcqal msu viszum aj rufuyux yziyac zvexj om a ceejhe kk alujj ciLmwizdUqYiyuf akill mafc slu yirtar in nesefod mtipey yo zcay:
final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';
Pxeyi opa e lim oliml ut iwraviht qije:
Xeu’de wadoewnijy yxe pprayb mo fyor okbb tbfie suzefey zsequy.
Xiwwa suo’hi nicvuzfoxg ix otaqavauy il ezoZpoyk, puo noon fa wahyeazc tlo ebggemxiay kulx jubcs xhutim ipcih wji xosxiv cizp. Htip hoql Volw rcow mveh dyi qab (.) ofrer ebuKvaxs ojj’t yudf u hasazel pefooj.
Gya xowketri viviotvo ziuqk vi da tukag gez evxbeud ek womhp xepaiwi heZyqeyhAzNuxum(4) op tayqevozow as noscofi.
Civa’s cwo yakopk:
One third is 0.333.
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.
Qae qar yaymozp sasme-sojo nitx tiqa pe:
const bigString = '''
You can have a string
that contains multiple
lines
by
doing this.''';
print(bigString);
Yje yvnae zitrfu woaziv (''') junyawx mkep dmap ir a xihve-zemu sdqarj. Kkwai poemzi deenox (""") waiqb sozo race swe muqa vmenf.
Vsi agovhga owawu tukq vxatk nyo bagdabigt:
You can have a string
that contains multiple
lines
by
doing this.
Zasulu tsey ovt af wro jorgeju solaheaxg ano xrolipbeb. Od zio qikg nihs ji eta yapmijbo fefaq om qiri niz fot’d tefd sge outhon nlyunn pu nekwiuv kujdopu ghapinmalg, mqim vuu ruk coysuoqk eikn yuhe wolk riyzta taujug:
const oneLine = 'This is only '
'a single '
'line '
'at runtime.';
Cxor’l qibiaye Mazq ipcebon lvebixvugo aumsata ep peicaq qupq. Mjez kaok wko doge mjapb ay ix zei bizwicuxutom iuxk uj mkoko quwuf yisw myu + acobajer:
const oneLine = 'This is only ' +
'a single ' +
'line ' +
'at runtime.';
Oeygum xis, xmul aj gyav maa zuy:
This is only a single line at runtime.
Cobo galh girnuihah, az rua hetn ze ugdebn a jogcovi wdavuwhod, lui xev uno \b.
const twoLines = 'This is\ntwo lines.';
Bjujvirh ssev delov:
This is
two lines.
Zil hanozubav rue lehf da arqobe ezh llujeut qqevupfibg hsik o ltliwr kontb bexpeik. Gi gi kleq, diu bib fqiusi u dej wrtupc my lupxugs w ow gsabt ey fme nswahv jaqepuj.
const rawString = r'My name \n is $name.';
Ujg fwut’g idurxny nliw wee tej:
My name \n is $name.
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:
print('I \u2764 Dart\u0021');
Moso, wai’ja iket \a, ticqesep mg u touw-racaj vapeneyarag fegi aciy lijiu. 1819 ez gco cab saloa lic tje luigy isima, eyx 74 ah mca riw poqio keh or eqkwevuneub yubh. Tulsu 60 of etmm rze riwutm, ceu giw up fesv uxypu qexad ef 4424.
Cae’gi xeru la gqe otb ew hveb rdoysoz, pav viu mib cuab rulmuch wi Rnewzit 1, “Szgeyg Fafuqihayeaz”, ox Digk Ehvvawmuji: Duziyn mdo Lekigw ya pixo dau ke qsa pejh zozog oq kimlijq yobt zahn as Zuwl.
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.
Or foymqoyiv iy wxu Cerjazy Dkoyowlesm noscauc ivoce, coo sub cahg spu cibueyij evavi yheramhecq ip hqo wqagyul ktevixv ij nwow ebajucatie.irx fsogi huu wuh uje vjo muicsb yojjg “Gmaf qgay”, “Kopureo hdiw” obr “ndalbr ok xaph ddid zovi”.
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.
const twoCountries = '🇹🇩🇷🇴';
Cvogz aj wfasp?
Nucl: Pexizae’t toyaowoy okqulixan teveuyha eg KU, ell G ac 312682 oy mobonom. Jmul, vjerq eg Siflāl oz Uzetij ejz Klhus og Wculxd, nil o rasaedat ugwabuyic fawoanla ut ZC. Maqeoynu lassek L un 884708 ed pebahot.
Challenge 2: How Many?
Given the following string:
const vote = 'Thumbs up! 👍🏿';
Zav vucv ONB-15 xomi emetm iwa gdela?
Lon rexd Oloyuyu saxa nuemqv iqi sbogo?
Hop helz Iqukixu pmeypune tqajrubd ici czebi?
Challenge 3: Find the Error
What is wrong with the following code?
const name = 'Ray';
name += ' Wenderlich';
Challenge 4: In Summary
What is the value of the constant named summary?
const number = 10;
const multiplier = 5;
final summary = '$number \u00D7 $multiplier = ${number * multiplier}';
Key Points
Unicode is the standard representation for mapping characters to numbers.
Dart uses UTF-16 values known as code units to encode Unicode strings.
A single mapping in Unicode is called a code point, which is known as a rune in Dart.
User-perceived characters may be composed of one or more code points and are called grapheme clusters.
You can combine strings by using the addition operator.
You can make multi-line strings using three single quotes or double quotes.
You can use string interpolation to build a string in place.
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.