Categories
linuxhint.com

How to use C++ String Class

A class is a set of variables and functions that work together; where the variables do not have values assigned to. When values are assigned to the variables, the class becomes an object. The difference between the string collection and an array, is, that the string collection can grow in length or shrink in length. A string object is instantiated (constructed) from a string class. A string object is a data structure with member functions. In this article, how to use C++ String Class is explained.

A string literal is a sequence of characters in a constant array pointer terminated by the nul character, . When identified, by a variable, the string literal cannot really reduce or increase in length. Many operations cannot be done on the string literal. So, there is a need for a string class. The C++ string class is for a data structure, a collection of characters in sequence, which allows member functions and operators to act on the characters. The string class allows more manipulations on the corresponding string literal, than just the string literal. You need to have good knowledge of string literal, to understand this article.

Class and Objects

A class is a set of variables and functions that work together; where the variables do not have values assigned to. When values are assigned to the variables, the class becomes an object. Different values given to the same class result in different objects; that is, different objects are the same class with different values. Creating an object from a class is said to be instantiating the object.

The name, string, is a class. An object created from the string class has a programmer chosen name.

A function that belongs to the class is needed to instantiate an object from the class. In C++, that function has the same name as the name of the class. Objects created (instantiated) from the class have different names given to them, by the programmer.

Creating an object from a class means constructing the object; it also means instantiating.

A C++ program which uses the string class, starts with the following lines at the top of the file:

#include <iostream>
#include <string>
using namespace std;

The first line is for input/output. The second line is to allow the program to use all the features of the string class. The third line allows the program to use the names in the standard namespace.

Overloading a Function

When two or more different function signatures have the same name, that name is said to be overloaded. When one function is called, the number and type of arguments, determine which function is executed.

Construction

string()
The following statement constructs a string of zero length with no character.

string strCol = string();

It begins with the name of the class (object type), string. This is followed by the name for the object string, given by the programmer. The assignment operator follows; then the name of the constructor with empty parentheses. Here, strCol is the instantiated object with all the data members (properties) and member functions (methods).
string(str)
This is similar to the above, but takes either a string literal or an identifier as an argument, in the constructor. The following statement illustrates this:

string strCol = string(“I love you”);

Construction with Initializer List

The following code illustrates this:

string strCol = string({‘I’,‘ ‘,‘l’,‘o’,‘v’,‘e’,‘ ‘,‘y’,‘o’,‘u’,});

The string literal is “I love you”. Note the nul character at the end of the initializer list.

string(str, n)

This forms a string collection, of the first n characters of another string. The following code illustrates this:

char str[] = “I love you”;
string strCol = string(str, 6);
cout << strCol << n;

The output is “I love†with the first 6 characters from “I love youâ€. Remember: the single space is a character.

string(str, pos, n)

This forms a string collection of n characters, beginning from the zero-based indexed position, pos, of another string. The following code illustrates this:

char str[] = “I love you”;
string strCol = string(str, 2, 4);
cout << strCol << n;

The output is, “loveâ€.

For the above two cases, if n is greater than the size of the string, the out_of_range exception is thrown – see later.

string(n, ‘c’)

Forms a collection of n characters, where all the characters are the same. Consider,

string strCol = string(5,‘e’);
cout << strCol << n;

The output is, “eeeeeâ€, 5 e’s.

Assigning a String

A string can be assigned as follows, after having declared both strings:

string strCol1 = string(“I love you”);
string strCol2;
strCol2 = strCol1;
cout << strCol2 << n;

The output is, “I love you”.

Constructing with Iterator

An iterator provides a generic representation of scanning, through the values of a collection. A syntax to create a string with iterator, is:

template<class InputIterator>
basic_string(InputIterator begin, InputIterator end, const Allocator&
 a = Allocator());

This constructs a string for the range [begin, end) – see details later.

Destroying a String

To destroy a string, just let it go out of scope.

String Class Element Access

An instantiated string object can be sub-scripted (indexed) like an array. Index counting begins from zero.

stringName[i]

The operation “stringName[i]†returns a reference to the character (element) at the ith index of the character collection. The following code outputs v:

string strCol = string(“I love you”);
char ch = strCol[4];
cout << ch << n;

stringName[i] const

The operation “stringName[i] const†is executed instead of “stringName[i]†when the string object is a constant object. It is used in the following code for example:

const string strCol = string(“I love you”);
char ch = strCol[4];
cout << ch << n;

The expression returns a constant reference to the ith element of the string object. None of the elements of the string can be changed.

Assigning a Character with Subscript

A character can be assigned to a non-constant string object, as follows:

string strCol = string(“I call”);
strCol[2] = ‘f’;
cout << strCol << n;

The output is “I fallâ€. ‘c’ was changed to ‘f’.

stringName.at(i)

“stringName.at(i)†is similar to “stringName[i]â€, but “stringName.at(i)†is more reliable. The following code shows how it should be used:

string strCol = string(“I love you”);
char ch = strCol.at(4);
cout << ch << n;

at() is actually a string class member function.

stringName.at(i) const

“stringName.at(i) const†is similar to “stringName[i] constâ€, but “stringName.at(i) const†is more reliable. “stringName.at(i) const†is executed instead of “stringName.at(i)†when the string object is a constant string object. It is used in the following code, for example:

const string strCol = string(“I love you”);
char ch = strCol.at(4);
cout << ch << n;

“at() const†is actually a string class member function.

Assigning a Value with the at() Function

A value can be assigned to a non-constant string object, with the at() function, as follows:

string strCol = string(“I call”);
strCol.at(2) = ‘f’;
cout << strCol << n;

The output is “I fallâ€.

Problem with Sub-scripting

The problem with sub-scripting (indexing) is, that if the index is out of range, the wrong result may be obtained, or an error may be issued at run-time.

front()

This returns a reference to the first element of the string object, without removing the element. The output of the following code is ‘I’.

string strCol = string(“I love you”);
char ch = strCol.front();
cout << ch << n;

The character is not removed from the string object.

front() const

When the string object construction is preceded by const, the expression “front() const†is executed instead of “front()â€. It is used in the following code, for example.

const string strCol = string(“I love you”);
char ch = strCol.front();
cout << ch << n;

A constant reference is returned. The element is not removed from the string object. No character can be changed for a constant string object.

back()

This returns a reference to the last element of the string object, without removing the element. The output of the following code is ‘u’.

string strCol = string(“I love you”);
char ch = strCol.back();
cout << ch << n;

back() const

When the string object construction is preceded by const, the expression “back() const†is executed instead of “back()â€. It is used in the following code, for example.

const string strCol = string(“I love you”);
char ch = strCol.back();
cout << ch << n;

A constant reference is returned. The element is not removed from the string object.

String Capacity

size_type capacity() const noexcept

The total number of characters the string can hold without requiring reallocation, is returned by this capacity member function. A code segment for this is:

string strCol = string();
int num = strCol.capacity();
cout << num << n;

The output is 15 on my computer.

reserve(n)

Memory space is not always available in free store. Extra space can be reserved in advance. Consider the following code segment:

string strCol = string(“love”);
strCol.reserve(6);
cout << strCol.capacity() << n;

The output is 15 on my computer.

size() const noexcept

This returns the number of characters in the string. The following code illustrates:

string strCol = string(“I love you”);
int num = strCol.size();
cout << num << n;

The output is 10, which does not include the nul, character.

length() const noexcept

same as size().
Note: size() <= capacity() .

shrink_to_fit()

Can reduce capacity() to size() by causing reallocation; it is not obligatory. The following code demonstrates this:

string strCol = string(“I love you”);
strCol.reserve(12);
strCol.shrink_to_fit();
int sz = strCol.size();
cout << sz << n;

The output is 10 and not 12 or 16. The function returns void.

resize(sz), resize(sz,’c’)

This resizes the string. If the new size is smaller than the old size, then the elements towards the end are erased. If the new size is longer, then some default character is added towards the end. To have a particular character added, use the resize() function with two arguments. The following code segment illustrates the use of the two functions:

string strCol = string(“I love you”);
strCol.resize(6);
cout << “New size of strCol: “ << strCol.size() << n;
string strCol1 = string(“I love”, ‘e’);
strCol1.resize(12);
cout << “New size of strCol1: “ << strCol1.size() << n;

The output is:

New size of strCol: 6
New size of strCol1: 12
The function returns void.

clear() noexcept

Removes all elements from the string, as the following code segment illustrates:

string strCol = string(“I love you”);
strCol.clear();
cout << strCol.size() << n;

The output is 0. The function returns void.

empty() const noexcept

This returns 1 for true if there is no character in the string object, or 0 for false if the string object is not empty. The following code illustrates this:

string strCol1 = string(“I love you”);
cout << strCol1.empty() << n;
string strCol2 = string();
cout << strCol2.empty() << n;

The output is:

0
1

Returning Iterators and the String Class

An iterator is like a pointer but has more functionality than the pointer.

begin() noexcept

Returns an iterator that points to the first character (element) of the string object, as in the following code segment:

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.begin();
cout << *iter << n;

The output is ‘I’. Note the way the declaration that receives the iterator, has been declared. The iterator is dereferenced in a return expression to obtain the value, in the same way, that a pointer is dereferenced.

begin() const noexcept;

Returns an iterator that points to the first element of the string object collection. When the object construction is preceded by const, the expression “begin() const†is executed instead of “begin()â€. Under this condition, the corresponding element in the object cannot be modified. It is used in the following code, for example.

const string strCol = string(“I love you”);
basic_string<char>::const_iterator iter = strCol.begin();
cout << *iter << n;

The output is ‘I’. Note that const_iterator has been used this time, instead of just iterator, to receive the returned iterator.

end() noexcept

Returns an iterator that points immediately beyond the last element of the string object. Consider the following code segment:

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.end();
cout << *iter << n;

The output is null, which is nothing, as there is no concrete element beyond the last element.

end() const noexcept

Returns an iterator that points immediately beyond the last element of the string object. When the string object construction is preceded by const, the expression “end() const†is executed instead of “end()â€. Consider the following code segment:

const string strCol = string(“I love you”);
basic_string<char>::const_iterator iter = strCol.end();
cout << *iter << n;

The output is null. Note that const_iterator has been used this time, instead of just iterator, to receive the returned iterator.

Reverse Iteration

It is possible to have an iterator that iterates from the actual end to just before the first element:

rbegin() noexcept

Returns an iterator that points to the last element of the string instantiated object, as in the following code segment:

string strCol = string(“I love you”);
basic_string<char>::reverse_iterator iter = strCol.rbegin();
cout << *iter << n;

The output is ‘u’. Note the way the declaration that receives the reverse iterator, has been declared. The iterator is dereferenced in a return expression to obtain the value, in the same way, that a pointer is dereferenced.

rbegin() const noexcept;

Returns an iterator that points to the last element of the string object. When the object construction is preceded by const, the expression “rbegin() const†is executed instead of “rbegin()â€. Under this condition, the corresponding element in the object cannot be modified. The feature is used in the following code, for example.

const string strCol = string(“I love you”);
basic_string<char>::const_reverse_iterator iter = strCol.rbegin();
cout << *iter << n;

The output is ‘u’. Note that const_reverse_iterator has been used this time, instead of just reverse_iterator, to receive the returned iterator.

rend() noexcept

Returns an iterator that points just before the first element of the string object. Consider the following code segment:

string strCol = string(“I love you”);
basic_string<char>::reverse_iterator iter = strCol.rend();
cout << *iter << n;

The output is null, which is nothing, as there is no concrete element just before the first element.

rend() const noexcept

Returns an iterator that points just before the first element of the string object. When the object construction is preceded by const, the expression “rend() const†is executed instead of “rend()â€. Consider the following code segment:

const string strCol = string(“I love you”);
basic_string<char>::const_reverse_iterator iter = strCol.rend();
cout << *iter << n;

The output is null. Note that const_reverse_iterator has been used this time, instead of just reverse_iterator, to receive the returned iterator.

String Modifiers

A modifier that modifies the string object, can also take or return an iterator.

Appending

basic_string& operator+=(const basic_string& str)

Appends the right string object to the left string object. Example:

string strCol1 = string(“I love”);
string strCol2 = string(” you”);
strCol1 += strCol2;
cout << strCol1 << n;

The output is “I love youâ€. Do not forget that “strCol1 += strCol2†is same as “strCol1 = strCol1+strCol2â€.

basic_string& operator+=(const charT* s)

Appends a string literal to a string object collection. Example:

string strCol = string(“I love”);
strCol += ” you”;
cout << strCol << n;

Output: “I love youâ€.

basic_string& operator+=(charT c)

Appends a single character to an object string. Example:

string strCol = string(“I love yo”);
strCol += ‘u’;
cout << strCol << n;

Output: “I love youâ€.

basic_string& operator+=(initializer_list<charT>)

Appends an initializer list. Example:

string strCol = string(“I love”);
strCol += {‘ ‘,‘y’,‘o’,‘u’,};
cout << strCol << n;

Output: “I love youâ€. It is always good to add the nul, at the end of a character initializer list.

basic_string& append(const basic_string& str)

Appends the argument string object to the main string object. Example:

string strCol1 = string(“I love”);
string strCol2 = string(” you”);
strCol1.append(strCol2);
cout << strCol1 << n;

Output: “I love youâ€.

basic_string& append(const charT* s)

Appends a string literal argument to the main string. Example

string strCol = string(“I love”);
strCol = strCol.append(” you”);
cout << strCol << n;

Output: “I love youâ€.

basic_string& append(initializer_list<charT>)

Appends the initializer list, which is an argument, to the main string. Example:

string strCol = string(“I love”);
strCol = strCol.append({‘ ‘,‘y’,‘o’,‘u’,});
cout << strCol << n;

Output: “I love youâ€. It is always good to add the nul, character at the end of an initializer list.

basic_string& append(size_type n, charT c)

Appends n of the same character. Example:

string strCol = string(“tab”);
strCol = strCol.append(2, ‘o’);
cout << strCol << n;

Output: “tabooâ€.

basic_string& append(const charT* s, size_type n)

Appends the first n elements of a string literal to the main string object. Example:

string strCol = string(“I love”);
strCol = strCol.append(” you so”, 4);
cout << strCol << n;

The output is: “I love youâ€. If n is greater than the length of the literal, a length_error exception is thrown.

basic_string& append(const basic_string& str, size_type pos, size_type n = npos)

Appends n characters from the index, pos to the main string. Example:

string strCol = string(“I love”);
strCol = strCol.append(“ve you so”, 2, 4);
cout << strCol << n;

Output: “I love youâ€. An exception would also be thrown here, see later.

Assigning

basic_string& assign(const basic_string& str)

Assigns the argument string object to the main string, replacing any content that was there.

string strCol1 = string(“I love you”);
string strCol2 = string(“She needs me”);
strCol1 = strCol1.assign(strCol2);
cout << strCol1 << n;

Output: “She needs meâ€.

basic_string& assign(const charT* s)

Assigns a string literal argument to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”);
cout << strCol << n;

Output: “She needs meâ€.

basic_string& assign(initializer_list<charT>)

Assigns an initializer list argument to the main string, replacing any content that was there.
[cc lang=“c” escaped=“true” width=“780”]
string strCol = string(“I love you”);
strCol = strCol.assign({‘S’,‘h’,‘e’,‘ ‘,‘n’,‘e’,‘e’,‘d’,‘s’,‘ ‘,‘m’,‘e’,});
cout << strCol << n;

Output: “She needs meâ€. It is good to always add the nul, at the end of the character list, to form a string literal.

basic_string& assign(const charT* s, size_type n)

Assigns the first n characters of a string literal argument to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”, 9);
cout << strCol << n;

Output: “She needsâ€.

basic_string& assign(size_type n, charT c)

Assigns an argument of n of the same characters to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(4, ‘e’);
cout << strCol << n;

Output: eeee

basic_string& assign(const basic_string& str, size_type pos,
size_type n = npos)

Assigns n characters of a string object argument, beginning from pos, to the main string, replacing any content that was there.

string strCol = string(“I love you”);
strCol = strCol.assign(“She needs me”, 4, 5);
cout << strCol << n;

Output: “needsâ€. Would throw an exception – see later.

Inserting

basic_string& insert(size_type pos, const basic_string& str)

Inserts the string object argument to the main string, at index, pos.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate and “);
strCol1 = strCol1.insert(2, strCol2);
cout << strCol1 << n;

Output: “I hate and love youâ€. Would throw an exception – see later.

basic_string& insert(size_type pos1, const basic_string&
 str,size_type pos2, size_type n = npos)

Inserts a length of n characters from pos2 of string object argument, to the main string, at index, pos1.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate, want and need”);
strCol1 = strCol1.insert(2, strCol2, 6, 9);
cout << strCol1 << n;

Output: “I want and love youâ€.

iterator insert(const_iterator p, charT c)

Inserts a particular character, which is an argument, into the position pointed to by the iterator. Returns an iterator for the position of the newly inserted character.

string strCol = string(“I love you”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter; ++iter; ++iter; ++iter; ++iter;
basic_string<char>::iterator retI = strCol.insert(iter, ‘d’);
cout << *retI << n;
cout << strCol << n;

The output is:

‘d’

“I loved youâ€

iterator insert(const_iterator p, size_type n, charT c)

Inserts n of the same character of the argument, into the position, pointed to by the iterator. Returns an iterator for the position of the beginning of the newly inserted same characters.

string strCol = string(“Tab in the land.”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter; ++iter;
basic_string<char>::iterator retI = strCol.insert(iter, 2, ‘o’);
cout << *retI << n;
cout << strCol << n;

The output is:

‘o’

“Taboo in the land.”

 

basic_string& insert(size_type pos, const charT* s)

Inserts an argument string literal at the index, pos in the main string.

string strCol = string(“Tab in the land.”);
strCol = strCol.insert(3, “oo”);
cout << strCol << n;

Output: “Taboo in the land.”

basic_string& insert(size_type pos, const charT* s, size_type n)

Inserts the first n characters of the argument string literal, at the index, pos in the main string.

string strCol = string(“Tab in the land.”);
strCol = strCol.insert(3, “oooo”, 2);
cout << strCol << n;

Output: “Taboo in the land.”

Replacing

basic_string& replace(size_type pos1, size_type n1, const basic_string& str))

Replaces n1 characters in the main string object from index, pos1, with the argument string object.

string strCol1 = string(“I love you”);
string strCol2 = string(“hate you and”);
strCol1 = strCol1.replace(2, 4, strCol2);
cout << strCol1 << n;

Output: “I hate you and youâ€. Would throw an exception – see later.

basic_string& replace(size_type pos1, size_type n1, const basic_string&
 str,size_type pos2, size_type n2 = npos)

Replaces n1 characters in the main string object from the index, pos1, with n2 characters of the argument string object from the index, pos2.

string strCol1 = string(“I love you”);
string strCol2 = string(“we hate him and her”);
strCol1 = strCol1.replace(2, 4, strCol2, 3, 12);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos1, size_type n1, const charT* s,
 size_type n2)

Replaces n1 characters in the main string object from the index, pos1, with the first n2 characters of the literal string argument.

string strCol1 = string(“I love you”);
strCol1 = strCol1.replace(2, 4, “hate him and her”, 12);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos, size_type n, const charT* s)

Replaces n characters in the main string object from index, pos, with the literal string argument.

string strCol1 = string(“I love you”);
strCol1 = strCol1.replace(2, 4, “hate him and”);
cout << strCol1 << n;

Output: “I hate him and youâ€.

basic_string& replace(size_type pos1, size_type n1, size_type n2, charT c)

Replaces n1 characters in the main string object from the index, pos1, with n2 of the same character of the argument.

string strCol1 = string(“A bad tablet there.”);
strCol1 = strCol1.replace(9, 3, 2, ‘o’);
cout << strCol1 << n;

Output: “A bad taboo there.â€.

iterator erase(const_iterator p)

Removes a character at the position pointed to by the iterator; then returns the iterator position, which is now occupied by the character that was next to this character (or end()). The following code illustrates this:

string strCol = string(“abcd”);
basic_string<char>::iterator iter = strCol.begin();
++iter; ++iter;
strCol.erase(iter);
cout << strCol[0] << ‘ ‘ << strCol[1] <<
<< strCol[2]<< n;

The output: a b d

basic_string& erase(size_type pos = 0, size_type n = npos)

Removes n characters from the index, pos.

string strCol = string(“abcd”);
strCol.erase(1, 2);
cout << strCol[0] << ‘ ‘ << strCol[1] << n;

Output: a d

void push_back(charT c)

To add a single character at the end of the string:

string strCol = string(“abcd”);
strCol.push_back(‘5’);
cout << strCol << n;

Output: abcd5

void pop_back()

Removes the last character without returning it. The size of the string is reduced by 1.

string strCol = string(“abcde”);
strCol.pop_back();
cout << strCol << n;

Output : abcd

void swap(basic_string& s)

The literals of two string objects can be swapped.

string strCol1 = string(<a id=“post-69618-__DdeLink__781_3724385525”></a>“abcde”);
string strCol2 = string(“1234567”);
strCol1.swap(strCol2);
cout << strCol1 << n;
cout << strCol2 << n;

The output is:

“1234567”
“abcde”

String Operations

const charT* c_str() const noexcept

Returns a pointer to the first element of the string. The pointer can be incremented.

const string strCol = string(“abcde”);
const char* p = strCol.c_str();
cout << *p << n;
++p;
cout << *p << n;

Output is:

a
b

Because of the second const in the heading, the program cannot change any character in the string. The construction is preceded by const.

const charT* data() const noexcept

Returns a pointer to the first element of the string. The pointer can be incremented.

const string strCol = string(“abcde”);
const char* p = strCol.data();
cout << *p << n;
++p;
cout << *p << n;

Output is:

a
b

Because of the second const in the heading, the program cannot change any character in the string. The construction is preceded by const.

basic_string substr(size_type pos = 0, size_type n = npos) const

Returns a string object of n characters for the sub-string beginning from the index, pos.

const string strCol = string(“abcdefghij”);
const string retStr = strCol.substr(2, 4);
cout << retStr << n;

Output: cdef

find() Member Functions

size_type find(const basic_string& str, size_type pos = 0) const noexcept

Looks for a sub-string object beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“We are the world!”);
string strCol1 = string(“the”);
int num = strCol.find(strCol1, 2);
cout << num << n;

Output:

index: 7
Returns -1, when not found.

size_type find(const charT* s, size_type pos = 0) const

Looks for a sub-string literal beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“We are the world!”);
int num = strCol.find(“are”, 0);
cout << num << n;

Since “pos = 0†is the default, 0 in the argument could have been omitted.

Output: 3

Returns -1, when not found.

size_type find (const charT* s, size_type pos, size_type n) const

Looks for the first n characters of a sub-string literal beginning from the index, pos. If found, returns the beginning of the sub-string in the main string.

string strCol = string(“The biggest boy”);
int num = strCol.find(“bigger”, 1, 3);
cout << num << n;

Output: 4

Returns -1, when not found.

size_type find(charT c, size_type pos = 0) const

Looks for the character, c beginning from the index, pos. If found, returns the beginning of the sub-string in the main string. If not found, returns -1.

string strCol = string(“We are the world!”);
int num = strCol.find(‘z’);
cout << num << n;

Output: -1

The following reverse find() member functions exist:

size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;
size_type rfind(const charT* s, size_type pos = npos) const;
size_type rfind(const charT* s, size_type pos, size_type n) const;
size_type rfind(charT c, size_type pos = npos) const;

Comparison Member Functions

int compare(const basic_string& str) const noexcept

Compares the argument string object with the main string object. If the main string occurs before the argument (in the dictionary) it returns a positive number. If it occurs after the main string, it returns a negative number. If the two strings are the same, it returns zero.

string strCol1 = string(“crowd”);
string strCol2 = string(“people”);
int num = strCol1.compare(strCol2);
cout << num << n;

Output: -13

int compare(const charT* s) const

Same as above, but the argument is a string literal.

string strCol1 = string(“people”);
int num = strCol1.compare(“people”);
cout << num << n;

Output: 0

String Operators

These operators are applicable to string objects and not necessarily string literals.

+

Concatenates two string objects, and returns the concatenation.

string strCol1 = string(“dancing on”);
string strCol2 = string(” the moon”);
string strCol = strCol1+strCol2;
cout << strCol << n;

Output: “dancing on the moonâ€.

==

Returns 1 for true, if the string objects are the same; and zero for false, if they are not.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 == strCol2;
cout << bl << n;

Output: 0

!=

Returns 1 if the string objects are not the same, and zero if they are.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 != strCol2;
cout << bl << n;

Output: 1

<

Returns 1, if the left operand is less than the right operand according to the dictionary, or zero if it is not.

string strCol1 = string(“dancing on”);
string strCol2 = string(” on the moon”);
bool bl = strCol1 < strCol2;
cout << bl << n;

Output: 0

For ordinary characters in C++, in ascending order, numbers come before uppercase letters, which come before lowercase letters. The space character comes before zero and all of them.

C++ Main String Character Types

char

The char type is the original C++ type and would typically store a character in 8 bits.

char16_t

This stores a character in 16 bits.

char32_t

This stores a character in 32 bits.

wchar_t

char16_t and char32_t are wide characters. wchar_t is a wide-character that is proprietary and implementation-defined.

These types are called traits. However, C++ refers to them technically as, specializations of traits. This article has focused on the char type. The approach to the other types is slightly different – see later.

Other String Operation Member Functions

The signatures of other string operation functions are:

size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_of(const charT* s, size_type pos = 0) const;
size_type find_first_of(charT c, size_type pos = 0) const;
size_type find_last_of (const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_of (const charT* s, size_type pos, size_type n) const;
size_type find_last_of (const charT* s, size_type pos = npos) const;
size_type find_last_of (charT c, size_type pos = npos) const;
size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;
size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;
size_type find_first_not_of(const charT* s, size_type pos = 0) const;
size_type find_first_not_of(charT c, size_type pos = 0) const;
size_type find_last_not_of (const basic_string& str, size_type pos = npos) const noexcept;
size_type find_last_not_of (const charT* s, size_type pos, size_type n) const;
size_type find_last_not_of (const charT* s, size_type pos = npos) const;
size_type find_last_not_of (charT c, size_type pos = npos) const;

Conclusion

C++ has string literals and string objects. The string object has a collection of characters in sequence, similar to an array of characters in sequence. The difference between the string collection and an array, is, that the string collection can grow in length or shrink in length. A string object is instantiated (constructed) from a string class. A string object is a data structure with member functions. The member functions can be classified under the headings of object construction, element access, string capacity, string member functions with iterator arguments and return types, and string modifiers. String equality and relational operators also exist.

Leave a Reply

Your email address will not be published. Required fields are marked *