39
Numerical Conversions Strings in C++ CS 16: Solving Problems with Computers I Lecture #8 Ziad Matni Dept. of Computer Science, UCSB

Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

  • Upload
    others

  • View
    24

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

NumericalConversionsStringsinC++

CS16:SolvingProblemswithComputersILecture#8

ZiadMatni

Dept.ofComputerScience,UCSB

Page 2: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

5/1/18 Matni,CS16,Sp18 2

9

35

10

1617

28

15

5

GradeDistributionforMidterm#1CS16,Spring18(Matni)

AVERAGE(MEAN)=84.5%MEDIAN=87%

Page 3: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

LectureOutline

•  NumericalConversions– Binary,Octal,Hexadecimal

•  Strings– CStringsvs.C++Strings

5/1/18 Matni,CS16,Sp18 3

Page 4: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 5: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 6: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 7: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

5/1/18 Matni,CS16,Sp18 7

Page 8: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

25/1/18 Matni,CS16,Sp18 8

Page 9: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 10: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 11: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 12: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 13: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 14: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 15: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 16: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

5/1/18 Matni,CS16,Sp18 16

Page 17: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

WhatisaString?

•  Charactersconnectedtogetherinasequence

5/1/18 Matni,CS16,Sp18 17

H i M o m !

P i k a c h u

Page 18: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 19: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 20: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 21: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 22: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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 ?? ??

Page 23: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 24: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

TheStandardC++stringClass

•  Thestringsweknowandlove…•  Thestringclassallowstheprogrammertotreatstringsasabasicdatatype

–  NoneedtodealwiththeimplementationsofC-strings

•  Thestringclassisdefinedinthe<string>library

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

5/1/18 Matni,CS16,Sp18 24

Page 25: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 26: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 27: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 28: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

SearchFunctions:find 1

•  Youcansearchforathefirstoccurrenceofastringinastringwiththe.findfunction

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

5/1/18 Matni,CS16,Sp18 28

[7]

Page 29: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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]

Page 30: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 31: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

SearchFunctions:rfind

•  Youcansearchforathelastoccurrenceofastringinastringwiththe.rfindfunction

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

5/1/18 Matni,CS16,Sp18 31

[41]

Page 32: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 33: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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];

Page 34: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

ContentChangers:append

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

•  Doesthesamethingas:name1+name2

5/1/18 Matni,CS16,Sp18 34

Page 35: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 36: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 37: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

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

Page 38: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

YOURTO-DOs

q PrepareLab4forWednesday!q DoHW8bynextThursday

q VisitProf’sandTAs‘officehoursifyouneedhelp!

q Runamile.Ortwo.

5/1/18 Matni,CS16,Sp18 38

Page 39: Numerical Conversions Strings in C++ · Strings in C/C++ • Recall: C++ is based on C • Originally (in C), strings were defined as an “array of characters” – Called C-Strings

5/1/18 Matni,CS16,Sp18 39