pure C string

string initialization

in pure C, string is a char array terminating with NULL(‘\0’). To initialize an array of char(string) is with a string literal(a double-quotaed string).

in general, the string literal is used as the initializer for an array of char; anywhere else, it is a static array of chars, which shouldn’t be modified by a pointer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* initialize a string in C
* the size of s1 is taken from the size of the initializer
*/
char s1[] = "hello world" ;
// or
char s1[12] = "hello world";
/* common errors */
char s2[];
s2 = "hello world"
// error: storage size of 's2' isn't known
char s2[12];
s2 = "hello world"
// error: invalid array assignment
/* there is no "=" operator defined for char array in C
using strcpy()
*/
```
## char pointer arithmetic
```c
char s1[12];
*s1++ ;
/* error: lvalue requied as increment operand
* s3 is an array, can't modify the address of an array. the difference between pointer and array
*/
char* s2 = s1;
*s2++;
/* s2 is a pointer to s1, ++ is ok */

string.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* concatenate two strings */
strcat(char* s1, const char* s2) ;
strncat(char* s1, const char* s2, size_t n);
/* locate the first/last occurance of char c in string s */
strchr(const char* s1, int c);
memchr(const void* s1, int c, size_t n);
strrchr(const char* s1, int c);
/* compare s1 and s2 alphabetically */
strcmp(const char* s1, const char* s2);
strncmp(const char* s1, const char* s2, size_t n);
memcmp(const void* s1, const void* s2, size_t n);
/* copy s2 to s1 */
strcpy(char *s1, const char *s2);
memcpy(void* s1, void* s2, size_t n);
/* number of bytes, not including terminating NULL; sizeof() will inlcude the terminating NULL */
strlen(const char* s1);
/* find the first occurance of substring s2 in s1 */
strstr(const char *s1, const char *s2);
/* split string s1 into a sequence of tokens by s2 */
strtok(char* s1, const char* s2);

\ is replaced by in C++.
and be aware of downs of C string.