Empty string: Difference between revisions
Content added Content deleted
m (→{{header|C++}}) |
m (→{{header|C}}) |
||
Line 426: | Line 426: | ||
=={{header|C}}== |
=={{header|C}}== |
||
In C the strings are <code>char</code> pointers. A string terminates with the null char (U+0000, <code>'\0'</code>), which is not considered part of the string. Thus an empty string is <code>"\0"</code>, while a null string is a null pointer which points to nothing. |
In C the strings are <code>char</code> pointers. A string terminates with the null char (U+0000, <code>'\0'</code>), which is not considered part of the string. Thus an empty string is <code>"\0"</code>, while a null string is a null pointer which points to nothing. |
||
<lang C> |
<lang C>#include <string.h> |
||
/* ... */ |
|||
/* assign an empty string */ |
|||
const char *str = ""; |
const char *str = ""; |
||
/* to test a null string */ |
/* to test a null string */ |
||
if (str) { ... } |
if (str) { ... } |
||
/* to test if string is empty */ |
/* to test if string is empty */ |
||
if (str[0] == '\0') { ... } |
if (str[0] == '\0') { ... } |
||
/* or equivalently use strlen function |
/* or equivalently use strlen function |
||
⚫ | |||
strlen will seg fault on NULL pointer, so check first */ |
|||
⚫ | |||
/* or compare to a known empty string, same thing. "== 0" means strings are equal */ |
/* or compare to a known empty string, same thing. "== 0" means strings are equal */ |
||
if (strcmp(str, "") == 0) { ... } |
if (strcmp(str, "") == 0) { ... } |