String handling in C
From Wikiversity
[edit] C-style strings
There is no string type in the standard C language. However we have arrays, and we can use them to store characters. If we store a '\0' char right after the characters, we can use that as an EOS (end of string) character. Here we go we have a string! This solution is called a C-style string.
| H | e | l | l | o | \0 |
"Hello" stored as a C-style string
[edit] Using C-style strings
Declaration
Since C-style strings are basically character arrays, we declare them as such. Nothing complicated here, but you have to be aware that if you want your string to be n characters long, you need to declare an n+1 characters long character array because of the '\0' at the end.
char name[21];
Initialization There are 2 ways to give a string a(n) (initial) value.
- individual characters
- string literals (constants)
with the first method, we simply list the characters in the string one after another, but we shouldn't ever forget the terminating '\0'!
char name[21] = {'H','e','l','l','o'}; - WRONG
char name[21] = {'H','e','l','l','o','\0'}; - RIGHT
with the second method, we type in the string directly:
char name[21] = "Hello" ;
| Project: Topic:C |
| Previous: Pointers and Arrays — String handling in C — Next: Structs |