c-string is an array of chars which contains characters of string and terminates with 0"
char str[8] = "Hello";
Internally it will be:
1 2 3 4
|
0 1 2 3 4 5 6 7
'H' 'e' 'l' 'l' 'o' '\0' '█' '█'
^ ^
Garbage.
|
When we need to iterate over string we usually use for loop wuth condition "until current character is not zero":
1 2
|
for(int i = 0; str[i] != '\0'; ++i)
//Do something with str[i]
|
Or using the fact that 0 is false:
1 2
|
for(int i = 0; str[i]; ++i)
//Do something with str[i]
|
Or with pointers:
1 2 3 4 5 6 7
|
void do_something(char* str)
{
while(*str){
//do something
++str;
}
}
|
You cannot use assigment operator (aside from initialization) or others with c-strings, so you should use specific functions declared in <cstring>:
strncpy() to copy one string to another,
strncat() to contacenate twostrings,
strlen() to know string length...
Main error of many beginners is that they forget about trailing zero:
char x[5] = "Hello";//Error: Hello has 5 characters and another one needed for terminating zero!
Or forger to place it after string manipulation:
str[strlen(str)] = 'x';//Add 'x' at the end of line, overwriting zero character
More correct way:
1 2 3
|
int x = strlen(str);
str[x] = 'x';
str[x+1] = '\0';
|
However I did not do bounds cheching anywhere! It can lead to disasterous results.
You should account this too!
std::string is a class which wraps c-strings, so it becomes dynamically sized, safe and supports assigment by '=' operator, operator + to contacenate strings, and others...