In C, a string is a character array terminated by a null character \0, making its size one more than the number of characters. C++ also supports this, and the compiler automatically adds \0 when initializing the array.
Initializing a String in C++:
1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};
Memory representation of a string "Geeks" in C++.
Commonly Used Functions for C-Style Strings
C-style strings rely on a number of functions defined in the <cstring> header. Let's explore three common functions:
1. strlen (String Length)
The strlen function calculates the length of a string by counting characters until it encounters \0.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[] = "gfg";
char s2[] = {'C', 'P', 'P', '\0'};
cout << strlen(s1) << endl;
cout << strlen(s2) << endl;
return 0;
}
Output
3 3
Explanation:
- strlen ignores the null character while calculating the length.
- If the null terminator is missing, strlen may traverse unintended memory, causing incorrect results or runtime errors.
2. strcmp (String Comparison)
The strcmp function compares two strings lexicographically:
- Returns 0 if both strings are equal.
- Returns a negative value if the first string is smaller.
- Returns a positive value if the first string is greater.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s1[] = "gfg";
char s2[] = "abcd";
int result = strcmp(s1, s2);
if (result == 0) {
cout << "Same" << endl;
} else if (result < 0) {
cout << "Smaller" << endl;
} else {
cout << "Greater" << endl;
}
return 0;
}
Output
Greater
Explanation:
- Characters are compared one by one based on their ASCII values.
- Comparison stops as soon as a mismatch is found, or one string ends.
3. strcpy (String Copy)
The strcpy function copies the content of one string into another.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[5];
strcpy(str, "gfg");
cout << str << endl;
return 0;
}
Output
gfg
Explanation:
- strcpy copies characters, including the null terminator, from the source to the destination.
- Ensure the destination array has enough space to hold the source string and the null terminator.