Todayโs Outline
- Recap: char
- C string basics
- Reading and printing C strings
- Common string functions
- Safety of string functions
Recap: char
cstring vs std::string
cstring
- inherited from the C lang
string
- class defined in std lib
#include <string>
- Class and object
C String Basics
C String: '\\0'
- A C string is a char array terminated by
'\\0'
- Used to distinguish a C String from an ordinary char array
'\\0'
== null
C String: Declaration and Initialization
C String: Storage
Passing String to Functions
Reading and Printing C strings
Printing C Strings
Reading C Strings
Reading a Line: get() Loop
Reading a Line: getline()
Common cstring Functions
strlen()
strlen(str)
- returns the number of chars
strcpy()
strcpy(dst, src)
- copies src
into dst
strcat()
strcat(dst, src)
- concatenates src
into dst
strcmp()
strcmp(s1, s2)
- compare s1
and s2
until encountering different characters
< 0
if s1 < s2
in alphabet
> 0
if s1 > s2
in alphabet
0
if s1 == s2
Other String Functions
strncpy(dst, src, n)
strncat(dst, src, n)
strncmp(str1, str2, n)
strchr(str, ch)
/ strrchr(str, ch)
strstr(haystack, needle)
strspn(str, accept)
strcspn(str, reject)
Safety of String Functions
Additional Notes
strcpy
and strcat
are considered unsafe
, as they donโt check memory boundary
- Use
strcpy_s
and strcat_s
instead