/* * In general, only use C-style strings when you’re forced to. * C++ strings are much better. However, you occasionally encounter * old libraries that only have C-style interfaces. * * A C-style string is an array of chars. * * Because it’s a C array, it is NOT stretchy. It has the maximum length * that you gave it when you defined the array. If no length is given, * then the length is determined from the initializer. In either case, * the length of the array is fixed at compile time. * * The null (not NULL) character, '\0', indicates the end of the string. * There may be extra room in the array--that’s ok. Therefore, the length * of the string may be different than the length of the containing aray. * * C strings have no methods, because they’re arrays, not objects. Use * the strlen function, defined in , to get a C string’s size. * strlen("Jack") is 4, not 5. * * A C++ string object has no fixed length. Null chars are not special. * Unlike Java, you can change the string. * Unlike Java, the string object is NOT dynamically allocated via new. * Use the .size() method to calculate the length of a C++ string object. * * For both C++ and C-style strings, use subscripting to access * individual characters. A method exists to access individual chars * of a C++ string, but only Java buffoons use it. */ #include #include // C++ std::string object #include // C string routines using namespace std; int main() { char q[80] = "This is a C-style string.\n"; cout << q; char r[] = "foobar"; r[3] = '\0'; cout << "r is now \"" << r << "\"\n"; const char *p = "This is also a C-style string"; cout << p << ", length is " << strlen(p) << '\n'; string s("useless initial value"); s = "This am a C++ std::string object"; // std::string = const char * s[5] = 'i'; // Mutable, unlike Java s[6] += 6; // char is integer-like cout << s << ", length is " << s.size() << '\n'; return 0; }