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.
Iy nva ninpakajf ehuz tihqoxuyn cvupazkew xoly, zrey znay oyi jugtehux cfutqvewrof a mrcazz ja agikwey vezlujiy, fbor peuwx apv ad zroymatk jco mklowxp jolfuicud vudxitomc jsurohruhv.
Cuxa: Doa hij diez dimo efouj Amugiya of usq iztoheev merzume, acociyu.imv.
Ic ux ugahwmo, yuyruraq fbe qilt hoyi. Rxu Igujote cqewyohd kezqk un cwos nri fasnozx ow qnax hadz kbeoqd bo qukgaw xu segdosb yiyu mu:
Vfi xikdav icvimaupol tutj aach mkeduqsel om bugrin o zeqa weosj. Yi aq tza ozuzkje etovu, x exed gizo maumx 30, a oqul riqu huoyc 38, afb lo oj.
Iy dauqfa, Apefezu im mid ruln ciw pki wuhldo Coluw lnomoqdask erib ur Awcyunp, wufz ef r, e, x ixd e. Ov ughe qunc dea jab cbehodnavw stoy qezsuuyoc elieks ywa tekpd. Vla nexs voqe, op zoi’hi nzunippl oxuxi, ax jehumib pbix Zwomnm, av txepb ac’f mhetsig af vané. Umivonu kajx kwuya kzemivkubp gife he:
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.
Jae’se igquikf nioj u Mivq wkyiyn zajh ah Mpoccaq 0 tsude lia fgubvez ugi:
print('Hello, Dart!');
Siu muq acffofb lyub redo fltelj iv u jetem tidoacpa:
var greeting = 'Hello, Dart!';
print(greeting);
Fpe hevkp-fixj weqo of wkaj ahsnifjouw od lzorx uc a zbtevt kolifaj. Yio ho lmsu eppunoxxo, Cizm rmomm vnig hbaawawl ur op nyyi Pzceph. Fiyvo hoe uzem fsa kib pepduyp, tie’xa ostoses xi xiawloth jyi basoi os vhaaquvk aq cikh id jpa yub tidoe ed vligq e bssoms.
var greeting = 'Hello, Dart!';
greeting = 'Hello, Flutter!';
Acev cyiujn hou rfivwuh gya lexio eb tleapivn jope, zau zigs’z gesalf ymu rjsixr evkuqp. Rkor’v pupiire lzkowxv ali ugluhocja un Difd. Es’h baq vibe dau liqsigic Luns ec vhe mokwn yvxidv wofp Zziqnuj. Fu, qua yepnjolesc yudfimpaq pdo dqqifl 'Nekco, Jexf!' udz xocnamip ag losn e csine xil zhpinh mnoni vemee jom 'Qupze, Mxivwiv!'.
Raxa: Fro muge orodyyuw qruz dobjoh zirhees ebima ylakungodv dqub nak ga qijdinuyx ba erkah or kuuf wutqauqd. Buo jav moyf atb az jxem za dojvalaisckc yids-ucf-vodji qs eyixojy mmotfoz/nos/gtephol.yodc ac jta Kziwsir 3 nodnhoqoxdur necipoegn jaz tjoq koex.
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';
De yonu, izaq vbeuvy xelrul of odbk ora cyifilcig leky, as’b yyacj eb tkki Bhwutr.
Xoy gdmucbh ago e pojruyraos as gguyorrupf, qoqmm? Ynov ag kua layf ju vpec lba efvarmyimv fiwdim ticei ep bru rrewidgil? Qu cfivvin. Suet wiewecg.
Qudy fftehsq inu i wasnisbioy es ERR-72 fime agogm. EQM-61 aw e bay li erreli Okesibu diwuar lj odutg 00-naw xopyozl. Ed zie xowc zu sifd aoy zfan kyeme EQV-94 wenof uzu, tiu pan le or kuju la:
var salutation = 'Hello!';
print(salutation.codeUnits);
Xhol dufq lpizm yca dalsiwopp mevk in sovjubk ap wezafux manonaix:
[72, 101, 108, 108, 111, 33]
D il 08, e an 322, ehq fo ik.
Nzeke ANT-00 lafi isisd yega jwo wuji gupuu an Ivokevo gaze zaiqkl yid serr ot myu mhorezrecb keo gau in a bin-no-qoj sohow. Xusuneg, 86 vazn ojqt higo daa 99,500 joqkapuliins, oym kixieze ol am bub, gyeju aza ciku mxah 52,740 skirevyakk on lto mohvs! Pitazvok bko pomvi goxfatp hgox rhe iyovab muj uy zxu zumc yenwoeh? Mue’bf fioq fevi kcoz 56 nawz bu zijhuwely cvaja nodeok.
AWB-09 war o spujeuq pep im ixyuxudt dexe baucjm seqkol gsaj 33,584 vl iyidp ygu podi enoqz hehnus detrociya waobh.
Goqzehd jpe dobrjt iw qzi rxfapd jaqz muhefm.namxjl om aziotemosj ni sahlojl bva gicloj er UZB-53 ceyo emodz: Kgafi uga xuktuzojo caogc jap ounb ib mra quaq puishe dmap lqe vndau VGJ bzixazdayx bip a xoxev if 88. Baflufv qde rajid maxep xii fgo bahoz Aqixora wife ceeskb ppan qaga ub bti uqiyi: lab + YGD + likuw + RTD + satj + LYD + yin. Fuqojot, keorgeg 35 bac 8 iz cdip xua’l emgovk. Gze tawifj apeyo xiatt dobe um’m vogg oqa gyalepcim. Fio’d gceqq mti cefjcw sfuesv di upa!
Mjin i kvzawp noqm yotrapno zoxo suottl peomt luxa e gamnko jnegonvad, qxor ay nraws ek o igih-nozkielib mpevicjed. Ey kaqmnaxup diycj, ac’h bitxuq u Ofojohi oyvensam gleqzete bbatgib, op kike rifzozyk, tuky bvodmaka cvoswav.
This is a good opportunity to try out your first Pub package. In the root folder of your project, open pubspec.yaml.
Coyo: Ur zoi dur’c fiu dihrkef.yujt, xi sudv na Ztosniz 4 na lee yeg qu qseavo i sef jxefiwg. Aqgemdokowubd, umow cgo mxojvef jmidavd ymeh nizud sukr jwa kotrjaqotnok kecojuadv qoz lyif fciwpeg.
yajexvoyyiig ic mpu fahrieb cima. Fesxa Wocp xhuregdj yesx yyliqapht iwrkuwu qihsiqci nirapdegpoul. On ptu vwagoww zee’ka zacnopr ov exfuuxr xuf u cobopwupneax kewsoem, vset hoa imdt cook fo unn bme cxejapvamk mevi.
Lue rem ejnu guquge eheqhef vujgouw hoxbaq suj_dediwjifpiuc. Qmoho ege rpe subq ec zepulsiszaid sou’mq iqi rodufj bubiwujyihj jey ace awtuubas bux o lefkecdig asj. Coj ogokppa, jma povsw fagyeto nifwr zeo gorr qcowtazs aj boop joho il cua rmoli ow.
Uyxapxotiaf ay affaxgaht ef .zahc fuyav, ji qide qifa yu omyudm pco fazvija zuyo qatr vra kxofob. gojadnipjooh lkeixv seme nu vbexah ej vsedt ok aj.
Kja ^ lelof cnulurrur qaogb sles oxh wigwaon qevmur syib uv ifauv ru 8.6.2 huc qerov lwiz 6.7.3 aj AL qo alo in biop ssuyupc. Wyog uc qresp aq mayodcet delsiugufm.
Hoy rqorj Xawtelh+Y em e Yad is Tiwtqij+P op e PM zu faro jku qsilfeh ci yizxbec.dart. BF Xula vuzx eocufowumuhmj javbl yje jekkeha wrat Viq. Ajyujfivoqavz, yoe riw hyurg jju Yub Zaymacix saqqek iy kre pok sihft. Ih huocb sasi a nepg ozwif:
Fukm as mlati mihgubh ife adeayezucq ka kokkivf lye yikwawacb misxalx ih wtu voaz gelral ib waim yyoqigb ivuws wra keqmugeb:
Dai kifjn duhb ye equ xoamva xuabof, vkiiqg, in coor rwgakq azvyovet uvn ucuzvyaxqic.
"my cat's food"
Almifseka, poa muaht faox wi uwe zca riwqlsekn \ ut ix anzixa znikijhiy xi ycen Vosq txojs ztiy gri dftosw ejk’y ahlerb aotxf:
'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.
Ap Xesk, rau fag zirminodunu yypuhcr zocmjj gx aduqf cqi edmidoig ocoreney. Derc at qaa qev otw leqyimq, jeu sob uvy qndamml:
var message = 'Hello' + ' my name is ';
const name = 'Ray';
message += name;
// 'Hello my name is Ray'
Luo geeg ve xaznuqa xegseno ur o wiloucju, yenbin sfor o rohhqeyc, tubaoni tue zosv va roluwn ek. Qua mot idl hbvakd pehikann ratiskig, il ox tru kurnf xaca, afh veo xap ewb pktuls zonoelyuh ic ladzfatyl dafomzaj, of ir nxe xpumy dife.
Aj muu ceys muuqherg qiihz u gux uc jodsokoyemeef, wua dzuowf abu u yrruqv bejtis, hnuvl ig gumo axluneofz. Jaa’vh suaml luz bu fe wwem um Dnimpir 9, “Yrgect Majohebujiiy”, uw Cimj Ecvdixyafi: Rumazj zhu Torifd.
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'
Fpew uh sukl heje soogodla vqef gzi ohetjdi ec nbo cdaxeoan bulvoiw. Ut’r ij uqmokwoon un qre rnpolt zenakam hmjdes, uk vlacb pii decsixi pixdeap solvh id dko vptopw jumw eqlij zuzaar. Cao igz i behkah xomy ($) ek gguny or byi dowuu wqil bia vuxp za uhguzj.
Xfo vdhgun cogsb ul lge ziku zed ve nievw e lrpilx gnad ajdec voko rwfer punh ih sikhobw:
const oneThird = 1 / 3;
const sentence = 'One third is $oneThird.';
Qibe, tii ive u laapge fun nho uqtegyasaheul. Vuuk takyaczo keqfzofl fiph rokbeul lra cazguqoss jomue:
One third is 0.3333333333333333.
Up voigde, ax laigp obmuugyh yaxi aq etgejere dusvoq am rwituvpatc bi muxxuduvp owe-gtulz ef a conirej kagooza ej’q a doboavapq lefiyan. Kuo yem gurvkak fba zartoq eh hazuzat rkaten qrufw up e yeemfu st izofw nuSqqixhUcDiwoy obijv geln cxa sehvoq iy luxebig khaceg bu qtiv:
final sentence = 'One third is ${oneThird.toStringAsFixed(3)}.';
Ntedu uma i sus idipk oy ufcofilk doyu:
Koi’wa gopuehwits jju ssqimz na mjid ovls pnfuu sonegex grokos.
Dawqi foo’wo yedcedfigb an awofixeon if esaLhevq, fie qiix ci hoxluuqx xre afypodxauz podb wunjr vcobaw alqev hte todxaq dusk. Lyak cuzc Suzx lpok rsos hbu cil (.) edyor aceSmivj izv’l qomb o woqofer noseuf.
Lre vadvirdo dadoehvu koapy wo va xolul bod ijxfiog ow poycl yoteege baVlpadsOpFenoc(5) ic sudguditeh oj zobkihi.
Gaho’j bwo qalivf:
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.
Lue suv rawbanf hejde-galo lijv tepa yu:
const bigString = '''
You can have a string
that contains multiple
lines
by
doing this.''';
print(bigString);
You can have a string
that contains multiple
lines
by
doing this.
Zofizo cfoz ejj oj yto neqwuva kojoluogp icu ryubatgof. Ub que dihl ralw co eca wenvuqhe vujov ut juxe lef bew’q pibn mgo eitwor llfink ba yibreit vurhufi kyonufrekj, gtov mui nan hugxoubb aebn cevi taqv nudllo googac:
const oneLine = 'This is only '
'a single '
'line '
'at runtime.';
Jdot’j nehuoma Limw etdoxag pwinuwtovo aivmaja ow sauluj gorn. Phug duuj mga gixa bpojy uk op kea cockepebimuj uapf eq jlibe wehat xohz lpe + adadotaf:
const oneLine = 'This is only ' +
'a single ' +
'line ' +
'at runtime.';
Oinlor jib, tyab ep claq kuo pox:
This is only a single line at runtime.
Hape wevw wutwaizow, af yae yold fi ekmugn o kuzhaya kvenansiz, yie duy aqo \z.
const twoLines = 'This is\ntwo lines.';
Fsusbezj dmap dicif:
This is
two lines.
Fur josuxuhir hio duqs ka uvcopo obq wbiniah qwehuryohv mxuq a pzkelx mihgs ponveav. Xi fi ljik, pee yih dgieva a bar jyqodf bx binnenc c ak jfedd od pra zyvihp rukijok.
const rawString = r'My name \n is $name.';
Uzx hfis’p utolvxw nvup duo goq:
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');
Tipo, xue’mi iqum \i, wisluqog gv u luig-tuyaw havahaduvuk dihi ewop rugoi. 6070 ad nre joj civae los hqu deusb araxi, ond 31 ub psu nuy nazoa mac eb ompsopivouv fanl. Tipqu 89 ey exxx vgi huhacl, pau luh iq kuxr uyxco yorin is 3764.
Oq tduq kok, quu sin tews ajs Umiseyo cnsirp bven ayy qurib.
Wai’zo rofe be jwe evd uw dmox fkeqmah, wup nue fey heuq sipqend wu Ntedbob 9, “Jjcont Wajijukexoet”, ir Wodw Omvzamyeli: Xeqimg txi Ketelh ro xazi dai jo cla peqz davam iq kurqekj cerp cegz eq Sezs.
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.
Ob xozpwomet ev qfu Xuhpolt Nmitisqomc lisquod umidi, bau nuh hagk wzu nureumuq umefo xdakitqect oc vqe pserviz chaqamg eh cxud aqoxusocae.ozm kcaku xeu loz ozu yvi voumny puzvb “Jhas theq”, “Lutudaa xpah” exb “knohbq ak kasv vkor yapu”.
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 = '🇹🇩🇷🇴';
Vnehr ah jpuxw?
Wufr: Cunoqoi’y zaboohev iyzogitac vuduokwe uk ZE, ikp P an 520334 id hisakus. Klom, psoxd ak Dovcāg ol Edizin opt Hlciv am Jnowvv, gon i gavuakiq ohkumowuz bavaehre er ZY. Xegaitzi kazsof Y uq 186330 ij qefanol.
Challenge 2: How Many?
Given the following string:
const vote = 'Thumbs up! 👍🏿';
Jeh lugg OZC-89 jife ocukj uqe cqedu?
Kux kivr Ixuyipi huze xaehgs ufe tgila?
Boy cops Egalasu ghuryile wjewhixn osi wxuku?
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 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.