String and pointer
C-String and Pointer
C-string (of the C language) is a character array, terminated with a null character '\0'. For example,// Testing C-string
#include
#include
using namespace std;
int main() {
char msg1[] = "Hello";
char *msg2 = "Hello";
// warning: deprecated conversion from string constant to 'char*'
cout << strlen(msg1) << endl; // 5
cout << strlen(msg2) << endl;
cout << strlen("Hello") << endl;
int size = sizeof(msg1)/sizeof(char);
cout << size << endl; // 6 - including the terminating '\0'
for (int i = 0; msg1[i] != '\0'; ++i) {
cout << msg1[i];
}
cout << endl;
for (char *p = msg1; *p != '\0'; ++p) {
// *p != '\0' is the same as *p != 0, is the same as *p
cout << *p;
}
cout << endl;
}
Take NOTE that for C-String function such as strlen() (in header cstring, ported over from C's string.h), there is no need to pass the array length into the function. This is because C-Strings are terminated by '\0'. The function can iterate thru the characters in the array until '\0'.
For example,
// Function to count the occurrence of a char in a string
#include
#include
using namespace std;
int count(const char *str, const char c); // No need to pass the array size
int main() {
char msg1[] = "Hello, world";
char *msg2 = "Hello, world";
cout << count(msg1, 'l') << endl;
cout << count(msg2, 'l') << endl;
cout << count("Hello, world", 'l') << endl;
}
// Count the occurrence of c in str
// No need to pass the size of char[] as C-string is terminated with '\0'
int count(const char *str, const char c) {
int count = 0;
while (*str) { // same as (*str != '\0')
if (*str == c) ++count;
++str;
}
return count;
}
Comments
Post a Comment