Friday, July 31, 2009

Why does C++ have a string class when there is already char * (a pointer to type character)?

A string is much more easier to work with than the char * due to the following reasons:


1. You have strict bounds checking in strings; char * doesn't have that.


2. If you need to equate two strings, you can just use the = symbol, not have to call the strcpy function everytime.


3. you can check for equality in an if condition ie u can use == to check if two strings are equal.


4. You can access individual characters by using the .at().


5. You needn't call strlen to check the length. all that need to be called is stringvariable.size().





There are a lot other advantages of using string class too. Ultimately, the string class scores on the ease of use. The char * scores on the raw power that it provides. You can use either depending upon your requirement and the time you are ready to devote to coding.

Why does C++ have a string class when there is already char * (a pointer to type character)?
Char is a single entity.......'a' , '1' etc.





But if u have a collection of characters together....."Bombay","computers"......


That is a string.


the space occupied is more 4 strings whereas character utilises only one byte.





Also way of use 4 chars and strs are different.String handling has a very huge application.However ,it should be noted that a string is an array of characters.


And use is so extensive that use of pointers can be sometimes tedious for the use of strings and is not always convenient and so we deal with string class independently though pointer can be used too.
Reply:char* strings are known as C strings. The usage of C strings is considerably more complex, not least because you have to be aware of memory issues.





With C++ strings for example, you can concatenate strings or place new strings in a string variable with little thought for the underlying memory handling. With char* strings, you better be aware of issues such as null-character termination, having enough buffer space when concatenating, and so on.





In short, C++ strings is a level or two above C strings in abstraction.


No comments:

Post a Comment