C++. Working with strings. The string class. Class constructors. The functions assign(), append(), insert(), replace(), erase(), find(), rfind(), compare(), c_str(). Examples




Working with strings. The string class. Class constructors. The functions assign(), append(), insert(), replace(), erase(), find(), rfind(), compare(), c_str(). Examples


Contents


Search other websites:

1. What is the purpose of the ‘string’ class in C++ programs?

The string class is intended for working with strings of type char*, which represent a null terminated string. The string class was introduced as an alternative for working with strings of type char*. The strings that end with ‘\0’ are also called C-lines. Because string is a class, you can declare objects of this class.

2. What modules (libraries) need to be connected to use the capabilities of the string class in MS Visual Studio C++?

To use the capabilities of the string class in MS Visual Studio (C++), you need to include the <string> library and the std namespace.

#include <string>
using namespace std;

3. How does it declare a variable of type ‘string’? Examples

The declaration of a variable of type ‘string’ is carried out in exactly the same way as a regular variable. Possible variant of the declaration with simultaneous initialization.

// the 'string' type
string s1; // variable named s1 of type 'string'
string s2 = "This is a string variable"; // declaration with initialization
// the using of variable of type 'string' with an assignment operator
s1 = s2; // s1 = "This is a string variable"
s2 = "New text";





4. What are the advantages and disadvantages of using the ‘string’ class in comparison with the char* type?

The creation of a new string type was due to the disadvantages of working with character strings, which the char* type demonstrated. In comparison with the type char*, the string type has the following main advantages:

  • the ability to process strings with standard C++ operators (=, +, = =, <>, etc.). As you know, when using char*, even the most simple operations with strings looked complicated and required writing excessive code;
  • ensuring the best reliability (security) of the program code. For example, when copying strings, the ‘string’ type provides the appropriate actions that can occur if the source string is larger than the receiver string;
  • providing the string as a separate data type. A ‘string’ type declaration as a string is the same for all variables in the program, which provides data consistency.

The main disadvantage of the ‘string’ type in comparison with the char* type is the slow processing speed. This is due to the fact that type ‘string’ is, in fact, a container class. And working with the class requires an additional implementation of the program code, which, in turn, takes extra time.

5. Which operators can be used with objects of class ‘string’?

The string class is convenient in that it makes it convenient to manipulate strings using standard (overloaded) operators. With objects of class string, you can use the following operations:

  • = – assignment
  • + – concatenation
  • += – assignment with concatenation
  • == – equality
  • != – inequality
  • < – less
  • <= – less or equal
  • > – grater than
  • >= – grater than or equal
  • [ ] – indexing

An example that demonstrates the use of the above operators

// the 'string' type, operations on strings
string s1 = "s-1";
string s2 = "s-2";
string s3;
bool b;

// operation '=' (assignment of strings)
s3 = s1; // s3 = "s-1"

// '+' operation - strings concatenation
s3 = s3 + s2; // s3 = "s-1s-2"

// '+=' operation - assignment with concatenation
s3 = "s-3";
s3 += "abc"; // s3 = "s-3abc"

// '==' operation - string comparison
b = s2==s1; // b = false
b = s2=="s-2"; // b = true

// '!=' operation - string comparison (not equal)
s1 = "s1";
s2 = "s2";
b = s1 != s2; // b = true

// operations '<' and '>' - string comparison
s1 = "abcd";
s2 = "de";
b = s1 > s2; // b = false
b = s1 < s2; // b = true

// operations '<=' and '>=' - strings comparison (less or equal, more of equal)
s1 = "abcd";
s2 = "ab";
b = s1 >= s2; // b = true
b = s1 <= s2; // b = false
b = s2 >= "ab"; // b = true

// operation [] - indexing
char c;
s1 = "abcd";
c = s1[2]; // c = 'c'
c = s1[0]; // c = 'a'

 

6. Does the ‘string’ class contain a constructors?

Like any class, the string class has a number of constructors. The main ones are:

string();
string(const char * str);
string(const string & str);

7. Examples of initialization using constructors

The following are examples of initializing variables of type ‘string’

string s1("Hello!"); // initialization - the constructor string(const char * str)
string s2 = "Hello!"; // initialization - the constructor string(const char * str)
char * ps = "Hello";
string s3(ps); // initialization
string s4(s3); // initialization - the constructor string(const string & str)
string s5; // initialization - the constructor string()

8. Assigning of strings. The assign() function. Examples

To assign one row to another, you can apply one of two methods:

  • use the assignment operator ‘=’;
  • use the assign() function from the string class.

The assign() function has several overloaded implementations.

The first option is to call a function without parameters

string &assign(void);

In this case, a simple assignment of one row to the other occurs.

The second option allows you to copy the specified number of characters from the string:

string &assign(const string & s, size_type st, size_type num);

where

  • s – the object from which the original string is taken;
  • st – the index (position) in the string from which the copying of num symbols begins;
  • num – the number of characters to be copied from st;
  • size_type – ordinal type of data.

The third variant of the function assign() copies the first characters (num) of the string s to the calling object:

string & assign(const char * s, size_type num);

where

  • s – a string that ends with the character ‘\0’;
  • num – the number of characters that are copied to the calling object. The first num characters in s string are copied.

Below is an example with different implementations of the assign() function.

An example.

// assignment of strings, function assign()
string s1 = "bestprog.net";
string s2;
string s3;
char * ps = "bestprog.net";

s3 = s1; // s3 = "bestprog.net"
s2.assign(s1); // s2 = "bestprog.net"
s2.assign(s1, 0, 4); // s2 = "best"
s2.assign(ps, 8); // s2 = "bestprog"

9. Merging strings. The append() function. Example

To merge strings, use the append() function. To merge strings can also use operation ‘+’, for example:

string s1;
string s2;
s1 = "abc";
s2 = "def";
s1 = s1 + s2; // s1 = "abcdef"

However, the append() function is well suited if you want to add part of a string.

The function has the following implementation options:

string &append(const string & s, size_type start);
string &append(const char * s, size_type num);

In the first embodiment, the function receives a reference to the string object s, which is added to the calling object. In the second implementation, the function receives a pointer to a string of type const char*, which is terminated by the character ‘\0’.

Example. Demonstration of the append() function.

string s1 = "abcdef";
string s2 = "1234567890";
s1.append(s2, 3, 4); // s1 = "abcdef4567"

char * ps = "1234567890";
s1 = "abcdef";
s1.append(ps, 3); // s1 = "abcdef123"

10. Inserting characters in a string. Function insert(). Example

To insert one string at a given position of another string, you need to use the insert() function, which has several implementation options.

The first variant of the function allows you to insert completely the entire string s into the specified position of the start of the calling string (calling object):

string & insert(size_type start, const string &s);

The second variant of the function allows you to insert the part (the parameters insStart, num) of the string s into the given start position of the calling string:

string & insert(size_type start, const string &s, size_type insStart, size_type num);

In the above functions:

  • s – a string that is inserted into the calling string;
  • start – position in the calling string from which to insert the string s;
  • insStart – position in the string s from which the insertion occurs;
  • num – the number of characters in the string s that are inserted from the insStart position.
string s1 = "abcdef";
string s2 = "1234567890";

s1.insert(3, s2); // s1 = "abc"+"1234567890"+"def"="abc1234567890def"
s2.insert(2, s1, 1, 3); // s2 = "12bcd34567890"

11. Replacing characters in a string. The replace() function. Example

The replace() function replaces the characters in the calling string. The function has the following implementation options:

string &replace(size_type start, size_type num, const string &s);
string &replace(size_type start, size_type num, const string &s, size_type replStart, size_type replNum);

In the first variant, the calling string is replaced by the string s. It is possible to specify the position (start) and the number of characters (num) in the calling string, which must be replaced by the string s.

The second variant of the replace() function differs from the first one in that it allows you to replace the calling string with only a part of the string s. In this case, two additional parameters are specified: the replStart position and the number of characters in the string s that form the substring. This substring replaces the calling string.

Example. Demonstration of the function replace().

string s1 = "abcdef";
string s2 = "1234567890";
s2.replace(2, 4, s1); // s2 = "12abcdef7890"

s2 = "1234567890";
s2.replace(3, 2, s1); // s2 = "123abcdef67890"

s2 = "1234567890";
s2.replace(5, 1, s1); // s2 = "12345abcdef7890"

// replacing of characters, the replace() function
string s1 = "abcdef";
string s2 = "1234567890";
s2.replace(2, 4, s1); // s2 = "12abcdef7890"

s2 = "1234567890";
s2.replace(3, 2, s1); // s2 = "123abcdef67890"

s2 = "1234567890";
s2.replace(5, 1, s1); // s2 = "12345abcdef7890"

s2 = "1234567890";
s2.replace(5, 1, s1, 2, 3); // s2 = "12345cde7890"

s2 = "1234567890";
s2.replace(4, 2, s1, 0, 4); // s2 = "1234abcd7890"

12. Removing the specified number of characters from the string. The erase() function. Example

To delete characters from the calling string, use the erase() function:

string &erase(size_type index=0, size_type num = npos);

where

  • index – the index (position), from which you need to delete characters in the calling string;
  • num – the number of characters that are deleted.

Example.

string s = "01234567890";
s.erase(3, 5); // s = "012890"
s = "01234567890";
s.erase(); // s = ""

13. Search for a character in a string. The functions find() and rfind(). Examples

In the ‘string’ class, you can do a string search in a substring in two ways that differ in the direction of the search:

  • by looking at the string from beginning to end with the find() function;
  • by looking at the string from the end to the beginning with the rfind() function.

The prototype of find() is:

size_type find(const string &s, size_type start = 0) const;

where

  • s – the substring that is searched in the string, which calls this function. The function searches for the first occurrence of the string s. If a substring of s is found in the string that called this function, then the position of the first occurrence is returned. Otherwise, -1 is returned;
  • start – the position from which the search is performed.

The prototype of rfind() is:

size_type rfind(const string &s, size_type start = npos) const;

where

  • s – the substring that is searched in the calling string. The search for a substring in a string is from the end to the beginning. If substring s is found in the calling string, then the function returns the position of the first occurrence. Otherwise, the function returns -1;
  • npos – the position of the last character of the calling string;
  • start – the position from which the search is performed.

Example 1. A snippet of code that uses the find() function

// the 'string' type, function find()
string s1 = "01234567890";
string s2 = "345";
string s3 = "abcd";
int pos;

pos = s1.find(s2); // pos = 3
pos = s1.find(s2, 1); // pos = 3
pos = s1.find("jklmn", 0); // pos = -1
pos = s1.find(s3); // pos = -1
pos = s2.find(s1); // pos = -1

Example 2. Using the rfind() function

// the 'string' type, functions find() and rfind()
string s1 = "01234567890";
string s2 = "345";
string s3 = "abcd";
string s4 = "abcd---abcd";

int pos;
pos = s1.rfind(s2); // pos = 3
pos = s1.rfind(s2, 12); // pos = 3
pos = s1.rfind(s2, 3); // pos = 3
pos = s1.rfind(s2, 2); // pos = -1
pos = s2.rfind(s1); // pos = -1
pos = s1.rfind(s3, 0); // pos = -1

// the difference between the find() and rfind() functions
pos = s4.rfind(s3); // pos = 7
pos = s4.find(s3); // pos = 0

14. Comparing the parts of strings. The compare() function. Example

Since type string is a class, you can use the ‘= =’ operation to compare two strings with each other. If two lines are the same, then the result of the comparison is true. Otherwise, the result of the comparison will be false.

But if you want to compare part of one string with another, then the function compare() is provided for this. The prototype of compare() function:

int compare(size_type start, size_type num, const string &s) const;

where

  • s – a string that is compared to the calling string;
  • start – the position (index) in the string s, from which the line of characters for comparison begins;
  • num – the number of characters in the string s that are compared with the calling string.

The function works as follows. If the calling string is less than the string s, then the function returns -1 (a negative value). If the calling string is greater than the string s, the function returns 1 (positive value). If two strings are equal, the function returns 0.

Example. Using the compare() function

// type string, function compare()
string s1 = "012345";
string s2 = "0123456789";

int res;
res = s1.compare(s2); // res = -1
res = s1.compare("33333"); // res = -1
res = s1.compare("012345"); // res = 0
res = s1.compare("345"); // res = -1
res = s1.compare(0, 5, s2); // res = -1
res = s2.compare(0, 5, s1); // res = -1
res = s1.compare(0, 5, "012345"); // res = -1
res = s2.compare(s1); // res = 1
res = s2.compare("456"); // res = -1
res = s2.compare("000000"); // res = 1

15. Getting a string with the end-of-line character ‘\0’ (char*). Function c_str(). Example

To get a string that ends with a ‘\0’ character, use the function c_str(). Function prototype:

const char * c_str() const;

Example 1. Converting ‘string’ type to const char *.

// the 'string' type, function c_str()
string s = "abcdef";
const char * ps;
ps = s.c_str(); // ps = "abcdef"

Example 2.

The following shows how to convert a ‘string‘ type to the System::String type to display it in a control of the Label type for applications such as Windows Forms Application.

// the 'string' type, function c_str()
string s = "abcdef";
String ss;
ss = gcnew String(s.c_str()); // converting
label1->Text = ss; // displaying on the form

16. How to determine the length of a string of type string? Function length()

To determine the number of characters in a string, the length() function is used without parameters.

Example.

string str = "Hello world!";
int len;

// determine the length of the string str
len = str.length(); // len = 12


Related topics