| Lesson 7 | String functions |
| Objective | Explore some of the functions in the cstring package. |
The C and C++ community has "agreed" to treat the type char* as a form of string type. The understanding is that these strings
will be terminated by the char value zero, and that the cstring package of functions will be called on this abstraction.
The language partly supports this abstraction by defining string literals as being null-terminated. A char* or char[] can be initialized with a literal string. Note that the terminating zero is part of the initializer list:
The language partly supports this abstraction by defining string literals as being null-terminated. A char* or char[] can be initialized with a literal string. Note that the terminating zero is part of the initializer list:
char* s = "c++"; // s[0] = 'c', s[1] = '+',
// s[2] = '+', s[3] = '\0';
The cstring package contains more than 20 functions, including:
By adhering to the above conventions, you will be able to reuse a lot of string code.
The library routines ensure that portable, readily understood code is available.
String Equality - Exercise
-
size_t strlen(const char* s);
Computes the string length. The number of characters before the null terminator 0 is returned. -
char* strcpy(char* s1,
const char* s2);
Copies the string s2 into s1. The value of s1 is returned. -
int strcmp(const char* s1,
const char* s2);
Returns an integer that reflects the lexicographic comparison of s1 and s2. When the strings are the same, zero is returned. When s1 is less than s2, a negative integer is returned. When s2 is less than s1, a positive integer is returned.
By adhering to the above conventions, you will be able to reuse a lot of string code.
The library routines ensure that portable, readily understood code is available.
Click the Exercise link below to write a function that implements a string equality test.
String Equality - Exercise
String Equality - Exercise