In C++, another way of representing an array of characters is using Strings class. Using string class gives many advantages over Character array like:
- The size of the array has to be predefined if it is getting allocated statically(char arr[3]). In this case, there might be unused bytes which results in inefficient memory usage. But, in string class size won't be wasted as memory is allocated on need basis.
- There is a possibility of array decay in an array of characters(Array decay happens usually when an array of characters is passed as by the value of reference and the type or dimension is changed). Whereas in string class such problems don't arise as it uses objects.
- Characters array doesn't provide many inbuilt functions to handle operations on strings. Whereas in the string there are many inbuilt functions to do operations.
- getline(cin, str): It is used to take input from the string. cin is also to take input of a set of characters but, it will stop accepting characters after space. getline() captures input until enter is recognized.
- str.push_back('z'): It concatenates the 'z' character at the end of the string str.
- str.pop_back(): It removes the last character from the string.
- capacity(): It returns the size of the memory allocated. It can be greater than the size of the characters so that if new characters are being inserted, it will be efficient.
- resize(): It changes the size of a string. With this, the size of the string can be increased or decreased based on the size given.
- length(): It returns the size of the string(doesn't include null character).
- shrink_to_fit(): As already discussed, the capacity of the string can be more than what is the actual size of the string. In order to shrink it so that the extra space is removed shrink_to_fit() is used.
- begin(): It returns the beginning pointer of the string
- end(): It returns the end pointer of the string.
- rbegin(): It returns the reverse iterator pointing at the end of the string.
- rend(): It returns the reverse iterator pointing at the start of the string.
- copy("character array", length, position): It copies the string into character array of size as length and starting position as position.
- swap(): It swap the two string.
Comments
Post a Comment