80 likes | 334 Views
C-Strings. Joe Meehean. C-style Strings. String literals (e.g., “foo”) in C++ are stored as const char[] C-style strings characters (e.g., ‘f’) are stored in an array of chars last char is the NULL character ‘’ or just plain 0 A hold over from C sometimes still used
E N D
C-Strings Joe Meehean
C-style Strings • String literals (e.g., “foo”) in C++ are stored as const char[] • C-style strings • characters (e.g., ‘f’) are stored in an array of chars • last char is the NULL character ‘\0’ or just plain 0 • A hold over from C • sometimes still used • important to know how they work char ca1[] = {‘C’, ‘+’, ‘+’}; // NO char ca2[] = {‘C’, ‘+’, ‘+’, ‘\0’}; // YES const char *cp = “C++”; // compiler adds ‘\0’
C-style Strings • Manipulated using (const) char* bool contains(const char* str, char& letter){ const char* p = str; while( *p != letter && *p != NULL ){ p++; } return( *p == letter ); } cout << contains(“Java”, ‘C’) << endl;
C-style Strings • Standard C library provides functions for C-style strings • intstrlen(const char *str) • returns length of str, not including null-terminator • intstrcmp(const char *a, const char* b) • returns 0 if a’s string and b’s string are identical • returns > 0 if a’s string > b’s string • returns < 0 if a’s string < b’s string
C-style Strings • Standard C library provides functions for C-style strings • char* strcat(char *destination, char* source) • appends source to destination • puts results into destination • e.g., strcat(“foo”, “bar”) = “foobar” • better have room in destination for strlen(destination) + strlen(source) + 1 characters • char* strcpy(char* dest, char* source) • copies source into destination • better have room in destination for strlen(source) + 1 characters
C-style Strings • Standard C library provides functions for C-style strings • char* strncat(char *destination, char* source, int n) • same as strcat, but only appends n characters • safer version of strcat • char* strncpy(char* dest, char* source, int n) • same as strcpy, but only copies n characters • safer version of strcpy
C-style Strings • Always use these n versions of string copy and concatenate • using strcpy and strcatcauses many, many security exploits • Always remember the null-terminator • strlen won’t work without it • can then cause strncpy & strncat to be wrong • OR, even better ALWAYS use C++’s string class