5
CS111 Lab Strings, continued Instructor: Michael Gordon

Strings2

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Strings2

CS111 LabStrings, continued

Instructor: Michael Gordon

Page 2: Strings2

Substrings

Use .substr() to get a substring

First parameter is starting index, second

(optional) is the number of characters in

the substring. (By default it is all of them.)

string s = “Ronald”;

cout<<s.substr(0); //prints Ronald

cout<<s.substr(0,3); //prints Ron

cout<<s.substr(1,2); //prints on

Page 3: Strings2

Insert and find

string s = “AM”;

string s1 = s.insert(1,”DA”);

Inserts “DA” into s starting at position 1.

cout<<s1; //prints ADAM

s.find(“AD”); //value of first position

Page 4: Strings2

Comparison

Use ==, <, >, !=, <=, >=

Comparison is on ASCII value, so ‘A’ < ‘a’, (‘A’ == 65 and ‘a’ == 97), so comparisons are most useful on all lower-case or all upper-case strings.

A useful tool is the toupper(c) is a function that takes a char parameter and returns the uppercase version.

Page 5: Strings2

Cstring equivalents

#include <cstring>

Cstrings are declared as char cs[] = ….

strlen(cs); //returns the length of cs

strcat(cs1,cs2); //concatenates two

cstrings