c string notes

3
strcpy(s, t); // strcpy(destination,source) strcpy(t, “abc”) cin.getline(s, 3) // 3 is the length of the string strlen(t) ; //length of string t compare string variables using C strings if (strcmp(s,t) == 0) strcmp(s,t) returns negative if s comes before t in the normal ordering 0 if s and t are identical up to the ‘\0’ positive if s comes after t in the normal ordering C++ strings: if (s<t) C strings: if (strcmp(s,t) < 0) if (s is equal to t( if (strcmp(s, t)) // Compiles but tests for != //C++ string void makeUpperCase(string& s) { for (int k=0; k!= s.size(); k++) s[k] = toupper(s[k]); } //C string void makeUpperCase(char s[]) { for (int k=0; s[k] != ‘\0’ ; k++) s[k] = toupper(s[k]); }

Upload: ben-quachtran

Post on 12-Apr-2015

6 views

Category:

Documents


0 download

DESCRIPTION

C String Notes

TRANSCRIPT

Page 1: C String Notes

strcpy(s, t); // strcpy(destination,source)strcpy(t, “abc”)cin.getline(s, 3) // 3 is the length of the stringstrlen(t) ; //length of string t

compare string variables using C stringsif (strcmp(s,t) == 0)

strcmp(s,t) returns negative if s comes before t in the normal ordering0 if s and t are identical up to the ‘\0’positive if s comes after t in the normal ordering

C++ strings: if (s<t)C strings: if (strcmp(s,t) < 0)

if (s is equal to t(if (strcmp(s, t)) // Compiles but tests for !=

//C++ string

void makeUpperCase(string& s){

for (int k=0; k!= s.size(); k++)s[k] = toupper(s[k]);

}

//C string

void makeUpperCase(char s[]){

for (int k=0; s[k] != ‘\0’ ; k++)s[k] = toupper(s[k]);

}

Page 2: C String Notes

0 1 2 3 4 5 60 ‘c’ ‘a’ ‘t’ ‘\0’

1 ‘m’ ‘o’ ‘u’ ‘s’ ‘e’ ‘\0’

2 ‘e’ ‘e’ ‘l’ ‘\0’

3 ‘f’ ‘e’ ‘r’ ‘r’ ‘e’ ‘t’ ‘\0’

4 ‘h’ ‘o’ ‘r’ ‘s’ ‘e’ ‘\0’

char pets[5][7] = {“cat”, “mouse”, “eel”, “ferret”, “horse”};cout << strlen(pets[0]); //outputs 3, the length of the string at row 0

pets[3] = pets[2]; //WRONG!! CANNOT ASSIGN ARRAYS MOTHERFUCKER

strcpy(pets[3], pets[2]); // copies pets[2] into pets[3]if (strcmp(pets[2],pets[3]) == 0) //true

const int MAXNAMES = 1000;const int MAXNAMELEN = 15;const int MAXLINELEN = 100;

int main(){

char names[MAXNAMES][MAXNAMELEN+1];int nNames = 0;

// read names, ending with an empty line

for (;;){

char s[MAXLINELEN];cin.getline(s, MAXLINELEN);if (strcmp(s, “”) == 0) //true if s is equal to empty string

break;if (strlen(s) > MAXNAMELEN)

{cout << “name is too long” << endl;continue; //abandon current loop iteration,continue to next}

if (nNames == MAXNAMES){

cout << “ … too many names …” << endl;}strcpy(names[nNames], s); nNames++;

}

Page 3: C String Notes

cout << “UCLA appears “ << tally(names, nNames, “UCLA”) << “ times.” << endl;}

int tally(const char a[][MAXNAMELEN+1], int n, const char target[]){

int total = 0;for (int k = 0; k < n; k++)

{if (strcmp(a[k],target) == 0)

total++;}

return total;

}