Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C •...

Preview:

Citation preview

NumericalConversionsStringsinC++

CS16:SolvingProblemswithComputersILecture#8

ZiadMatni

Dept.ofComputerScience,UCSB

5/1/18 Matni,CS16,Sp18 2

9

35

10

1617

28

15

5

GradeDistributionforMidterm#1CS16,Spring18(Matni)

AVERAGE(MEAN)=84.5%MEDIAN=87%

LectureOutline

•  NumericalConversions– Binary,Octal,Hexadecimal

•  Strings– CStringsvs.C++Strings

5/1/18 Matni,CS16,Sp18 3

CountingNumbersinDifferentBases•  We“normally”countin10s

–  Base10:decimalnumbers–  Numbersymbolsare0thru9

•  Computerscountin2s–  Base2:binarynumbers–  Numbersymbolsare0and1–  Representedwith1bit(21=2)

•  Otherconvenientbasesincomputerarchitecture:–  Base8:octalnumbers–  Numbersymbolsare0thru7–  Representedwith3bits(23=8)

–  Base16:hexadecimalnumbers–  Numbersymbolsare0thruF

•  A=10,B=11,C=12,D=13,E=14,F=15–  Representedwith4bits(24=16)–  Whyare4bitrepresentationsconvenient???

5/1/18 Matni,CS16,Sp18 4

PositionalNotationinDecimala.k.a.:HowILearnedNumbersin3rdGrade…

5/1/18 Matni,CS16,Sp18 5

642 is: 6 hundreds, 4 tens, and 2 units It’s a number in base 10 (aka decimal)

We can write it in positional notation:

= 6 x 100 = 600

= 4 x 10 = + 40 = 2 x 1 = + 2 = 642 in base 10

6x102+4x101+2x100

Whatif“642”isexpressedinthebaseof13?

So,“642”inbase13isequivalentto

“1068”inbase10

6 x 132 = 6 x 169 = 1014 + 4 x 131 = 4 x 13 = 52 + 2 x 13º = 2 x 1 = 2

= 1068 in base 10

PositionalNotationAnythingààDEC

5/1/18 Matni,CS16,Sp18 6

5/1/18 Matni,CS16,Sp18 7

25/1/18 Matni,CS16,Sp18 8

PositionalNotationinBinary

5/1/18 Matni,CS16,Sp18 9

11011 in base 2 positional notation is:

1 x 24 = 1 x 16 = 16 + 1 x 23 = 1 x 8 = 8 + 0 x 22 = 0 x 4 = 0 + 1 x 21 = 1 x 2 = 2 + 1 x 20 = 1 x 1 = 1

So, 1011 in base 2 is 16 + 8 + 0 + 2 + 1 = 27 in base 10

Q:Whatisthedecimalequivalentofthebinarynumber1101100?A:Lookforthepositionofthedigitsinthenumber.Thisonehas7digits,thereforepositions0thru6

ConvertingBinarytoDecimal

5/1/18 Matni,CS16,Sp18 10

1 x 26 = 1 x 64 = 64 + 1 x 25 = 1 x 32 = 32 + 0 x 24 = 0 x 16 = 0 + 1 x 23 = 1 x 8 = 8 + 1 x 22 = 1 x 4 = 4

+ 0 x 21 = 0 x 2 = 0 + 0 x 2º = 0 x 1 = 0

= 108 in base 10

1 1 0 1 1 0 064 32 16 8 4 2 1

26 25 24 23 22 21 20

OtherRelevantBases

•  InComputerScience/Engineering,otherbinary-relatednumericalbasesareusedtoo.

•  OCTAL:Base8 (notethat8is23)– Usesthesymbols:0,1,2,3,4,5,6,7

•  HEXADECIMAL:Base16 (notethat16is24)– Usesthesymbols:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

5/1/18 Matni,CS16,Sp18 11

ConvertingBinarytoOctalandHexadecimal(oranybasethat’sapowerof2)

•  Binaryis 1bit•  Octalis 3bits(23=8)octalisbase8•  Hexadecimalis4bits(24=16)hexisbase16

•  Usethe“groupthebits”technique– Alwaysstartfromtheleastsignificantdigit– Groupevery3bitstogetherforbinàoct– Groupevery4bitstogetherforbinàhex

5/1/18 Matni,CS16,Sp18 12

ConvertingBinarytoOctalandHexadecimal

•  Taketheexample:10100110…tooctal:

10100110…tohexadecimal:

10100110

5/1/18 Matni,CS16,Sp18 13

2 4 6

10 6

246inoctal

A6inhexadecimal

0

1

2

3

4

5

6

7

8

9

A

B

C

D

E

F

Octalsymbols

Hex.symbols

Decimalsymbols

While (the quotient is not zero) 1.  Divide the decimal number by the new base 2.  Make the remainder the next digit to the left in the answer 3.  Replace the original decimal number with the quotient 4.  Repeat until your quotient is zero

Algorithmforconvertingnumberinbase10tootherbases

ConvertingDecimaltoOtherBases

5/1/18 Matni,CS16,Sp18 14

EXAMPLE:Convertthedecimal(base10)number79intohexadecimal(base16)79/16=4R15(15inhexisthesymbol“F”)4/16=0R4

Theansweris:4F

ConvertingDecimalintoBinaryConvert54(base10)intobinaryandhex:•  54/2=27R0•  27/2=13R1•  13/2=6R1•  6/2=3R0•  3/2=1R1•  1/2=0R1

54(decimal)=(binary)=36(hex)

5/1/18 Matni,CS16,Sp18 15

Sanitycheck:110110=2+4+16+32=54

011011

5/1/18 Matni,CS16,Sp18 16

WhatisaString?

•  Charactersconnectedtogetherinasequence

5/1/18 Matni,CS16,Sp18 17

H i M o m !

P i k a c h u

StringsinC/C++

•  Recall:C++isbasedonC•  Originally(inC),stringsweredefinedasan“arrayofcharacters”

–  CalledC-Stringsandare“legacy”datatypesinC++–  Camewiththelibrary<cstring>–  Containslotsofbuilt-infunctionsthatgowithC-Strings

•  InC++,wegotanewlibrary:<string>•  Madeimprovementsovertheold“C-String”

–  LibrarycontainsanothercollectionoffunctionsthatworkwithStrings,butnotC-Strings!

5/1/18 Matni,CS16,Sp18 18

WhyDoWeCareAboutC-Strings??

•  TheiruseSTILLcomesupinC++– Recall:commandlinearguments…

•  Recallthatcommand-linearguments,specificallyargv[x]aredefinedas: char*[]

•  That’saclassicdefinitionofaC-String

– Soifwewanttousetheseargv[x],we’llhavetotreattheminaC-Stringfashion…

5/1/18 Matni,CS16,Sp18 19

Cstringsvs.C++strings

•  StringsinC++andStringsinC– C++ismeanttobebackwardscompatiblewithC– Chasonewayofdealingwithstrings,whileC++hasanother

•  C++’suseismucheasierandsaferwithmemoryallocation– Thisiswhatyou’velearnedsofarwith<string>– Let’sbrieflyreviewtheother(older)waywithC-strings…

5/1/18 Matni,CS16,Sp18 20

What’saC++ProgrammertoDo?!

•  AC-string– Anarrayofcharactersterminatedbythenullcharacter‘\0’–  ThenullcharacterhasanASCIIcodeof0.–  Libraryfordealingwiththesetypes:<cstring>

•  AC++stringobject– Aninstanceofa“class”datatype–useda“blackbox”–  Libraryfordealingwiththesetypes:<string>

5/1/18 Matni,CS16,Sp18 21

TheC-String•  Anarrayofcharactersthatterminatesinthenullcharacter

–  Thisterminatestheactualstring,butnotthearraynecessarily

•  Example:aC-stringstores“HiMom!”inacharacterarrayofsize10–  Thecharactersoftheword“HiMom!”willbeinpositionswithindices0to6–  Therewillbeanullcharacteratindex7,andthelocationswithindices8to9willcontainsomeunknownvalue.

–  Butwedon’tcareaboutpositions8and9!–  Thenullcharactersays“STOPHERE!”

5/1/18 Matni,CS16,Sp18 22

s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]

H i M o m ! \0 ?? ??

C-strings•  TodeclareaC-stringvariable,include<cstring>andusethissyntax:charArray_name[Maximum_C_String_Size+1];–  The“+1”reservestheadditionalcharacterneededby‘\0’

•  WithC-Strings,youcannotdothese: myString=“Hello!” //assignment if(myString==“Jimbo”)… //comparison

–  Insteadusestrncpy()andstrcmp()fromthe<cstring>library

•  ButyouCANuse=and==withC++Strings–  Andsomuchmoreusefulthings!J

5/1/18 Matni,CS16,Sp18 23

TheStandardC++stringClass

•  Thestringsweknowandlove…•  Thestringclassallowstheprogrammertotreatstringsasabasicdatatype

–  NoneedtodealwiththeimplementationsofC-strings

•  Thestringclassisdefinedinthe<string>library

•  Wewilldiscussmanydifferentmemberfunctionsthatareextremelyusefultouse–  Like.length(),.erase(),.substr(),.find(),etc…

5/1/18 Matni,CS16,Sp18 24

DeclaringaStringinC++

•  Youhavetoincludethecorrectlibrarymodulewith: #include<string>

•  Declarethem(andinitializethem)with: stringMyString=“”;//Notetheuseofdouble-quotes!

•  Sincestringsaremadeupofcharacters,youcanindexindividualcharactersinstrings(startingatposition0):

If MyString=“Hello!”ThenMyString[0]=‘H’,MyString[1]=‘e’,etc…

5/1/18 Matni,CS16,Sp18 25

StringBasics

•  Usethe+operatortoconcatenate2stringsstringstr1=“Hello”,str2=“world!”,str3;str3=str1+str2;//str3willbe“Helloworld!”

•  Usethe+=operatortoappendtoastringstr1+=“Z”;//str1willbe“HelloZ”

•  Calloutacharacterinthestringbasedonposition,using[]braces–  RecallarrayindicesinC++startatzero(0)cout<<str1[0];//printsout‘H’cout<<str2[3];//printsout‘l’

5/1/18 Matni,CS16,Sp18 26

Built-InStringMemberFunctions

•  Searchfunctions– find,rfind,find_first_of,find_first_not_of

•  Descriptorfunctions– length,size

•  Contentchangers– substr,replace,append,insert,erase

5/1/18 Matni,CS16,Sp18 27

SearchFunctions:find 1

•  Youcansearchforathefirstoccurrenceofastringinastringwiththe.findfunction

stringstr=“Withabanjoonmykneeandbanthebomb-ban!”;intposition=str.find(“ban”);cout<<position; //Willdisplaythenumber7

5/1/18 Matni,CS16,Sp18 28

[7]

SearchFunctions:find 2

•  Youcanalsosearchforathefirstoccurrenceofastringinastring,startingatpositionn,usingaslightmodto.find()stringstr=“Withabanjoonmykneeandbanthebomb-ban!”;intposition=str.find(“ban”,12);cout<<position; //Willdisplaythenumber28

5/1/18 Matni,CS16,Sp18 29

?[28]

SearchFunctions:find 3

•  YoucanusethefindfunctiontomakesureasubstringisNOTinthetargetstringusingthe“noposition”value

string::npos isreturnedifnopositionexistsif(MyStr.find("piano")==string::npos) cout<<"Thereisnopianothere!”//Thiswillhappenif“piano”isNOTinthestringMyStr

5/1/18 Matni,CS16,Sp18 30

SearchFunctions:rfind

•  Youcansearchforathelastoccurrenceofastringinastringwiththe.rfindfunction

stringstr=“Withabanjoonmykneeandbanthebomb-ban!”;intrposition=str.rfind(“ban”);cout<<rposition; //Willdisplaythenumber41

5/1/18 Matni,CS16,Sp18 31

[41]

SearchFunctions:find_first_ofandfind_first_not_of

•  find_first_of–  Finds1stoccurrenceofanyofthecharactersincludedinthespecifiedstring

•  find_first_not_of–  Finds1stoccurrenceofacharacterthatisnotanyofthecharacters

includedinthespecifiedstring

•  Example:

5/1/18 Matni,CS16,Sp18 32

Seedemofile:non_numbers.cpp

DescriptorFunctions:lengthandsize

•  Thelengthfunctionreturnsthelengthofthestring•  Thememberfunctionsizeisthesameexactthing…

–  So,ifstringstr1=“MamaMia!”, thenstr1.length()=9 andstr1.size()=9also

Example–whatwillthiscodedo?:

5/1/18 Matni,CS16,Sp18 33

stringname=“BubbaSmith”;for(inti=name.length();i>0;i--) cout<<name[i-1];

ContentChangers:append

•  Usefunctionappendtoappendonestringtoanotherstringname1=“Max”;stringname2=“Powers”;cout<<name1.append(name2); //Displays“MaxPowers”

•  Doesthesamethingas:name1+name2

5/1/18 Matni,CS16,Sp18 34

ContentChangers:erase

•  Usefunctionerasetoclearastringtoanemptystring

•  Oneuseis:name1.erase()--Doesthesamethingas:name1=“”

•  Anotheruseis:name1.erase(startposition,howmanycharstoerase)–  Erasesonlypartofthestring–  Example:strings=“Hello!”;cout<<s.erase(2,2);//Displays“Heo!”

5/1/18 Matni,CS16,Sp18 35

ContentChangers:replaceandinsert•  Usefunctionreplacetoreplacepartofastringwithanother

– PopularUsage:string.replace(startposition,#ofplacesafterstartpositiontoreplace, replacementstring)

•  Usefunctioninserttoinsertasubstringintoastring– PopularUsage:string.insert(startposition,insertionstring)

Example:stringcountry=“BackintheUSSR”; //lengthis16cout<<country.replace(14,2,“A”); //Displayscout<<country.insert(15,“BC”); //Displays

“BackintheUSABC”“BackintheUSA”

5/1/18 Matni,CS16,Sp18 36

ContentChangers:substr

•  Usefunctionsubstr(shortfor“substring”)toextractandreturnasubstringofthestringobject– PopularUsage:string.substr(startposition,#ofplacesafterstartposition)

Example:stringcity=“SantaBarbara”;cout<<city.substr(3,5)//Displays

“taBa”

5/1/18 Matni,CS16,Sp18 37

YOURTO-DOs

q PrepareLab4forWednesday!q DoHW8bynextThursday

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Runamile.Ortwo.

5/1/18 Matni,CS16,Sp18 38

5/1/18 Matni,CS16,Sp18 39

Recommended