Our instructor told us that a string is the array of characters, and I was wondering whenever we use any array statically, we have to define its size before compiling the pro-gramme in C++ then why don't we do same with the string? Thanks in advance.
3 Answers
The string is an object, which is smarter than a character array. A character array is just an allocation in memory, it has no logic associated with it. However the string (because it is an object) is able to manage its own memory and expand as needed. In C++ you can overload operators. Because the string class has its [ ] operators overloaded you can use the string as an array and access individual characters. However when you use the [ ] operators you are actually invoking a method on the string (namely operator[ ]).
So you can create a string, expand by adding to it, and access individual characters in it:
string str1 = "Hello "; // create a string and assign value
string str2("World"); // use the constructor to assign a value
str1 += str2; // append one string to another
cout << str1[0]; // should print H
But even though the opeartor overloading give it has the same feel as an array, it's actually an object.
Comments
if we talk about char* arr = "hello world"; now here "hello world" is given memory through a string object and the object is initialized by the constructor of the String class.
if we say String str = "hello world"; here again constructor of String class is called and it initializes the str object of String to point to the starting address of "hello world" which is stored somewhere in memory.
here we do not have to give the size, instead of that constructor of string class is doing all the trick of allocating dynamic memory and initializing.
std::stringclass, not arrays ofchar.std::stringis a class that encapsulates a "string". A C "string" in C++ is an array of characters, and must be declared with a size (e.g.char buffer[256]) or used as a string literal (e.g."Hello, World!") (not always interchangeable).cout << someString[3]. As for length, it would besomeString.length()or, for a c string,strlen(someString)