Menu
Is free
registration
home  /  Advice/ Term papers, laboratory papers and diplomas in computer science.

Term papers, laboratory papers and diplomas in computer science.

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

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

The string class is designed to work with strings of type char *, which are null-terminated strings. The string class was introduced as Alternative option for working with strings of type char *. Lines that end with a character ‘\0’ also called C-strings. Since 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 library and the std namespace.

#include using namespace std;
3. How is a variable of the string type declared? Examples of

Declaring a variable of type string is done in the same way as a regular variable. Possible variant simultaneous initialization declarations.

// string type string s1; // variable named s1 of type string string s2 = "This is a string variable"; // declaration with initialization // using a 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 versus char *?

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

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

The main disadvantage of the string type in comparison with the char * type is the slower data processing speed. This is because the string type is actually a container class. And working with a class requires additional implementation of the program code, which, in turn, takes extra time.

5. What operators can be used with objects of the string class?

The string class is convenient in that it allows you to conveniently manipulate strings using standard (overloaded) operators.

The following operators can be used with objects of the string class

  • = - assignment
  • + - concatenation (string concatenation)
  • += - assignment with concatenation
  • == - equality
  • != - inequality
  • < - smaller
  • <= - less than or equal to
  • > - more
  • >= - more or equal
  • - indexing

Example, which demonstrates the use of the above operators

// 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 "+" - string 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 "<" и ">"- string comparison s1 = "abcd"; s2 = "de"; b = s1> s2; // b = false b = s1< s2; // b = true // operations "<=" и ">= "- string comparison (less than or equal, greater than or 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; // c = "c" c = s1; // c = "a"
6. Does the string class contain constructors?

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

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

7. Examples of initialization using constructors

Below are examples of initializing variables of type string

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

8. Assignment of strings. Assign () function. Examples of

To assign one string to another, you can use one of two methods:

  • use 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, there is a simple assignment of one string to another.

The second option allows you to copy a given number of characters from a string:

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

  • s - the object from which the source string is taken;
  • st - index (position) in the string from which to start copying num characters;
  • num - the number of characters to copy from position st;
  • size_type is an ordinal data type.

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

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

  • s - a string terminated with a character ‘\0’ ;
  • num is the number of characters that are copied to the caller. The first num characters from string s are copied.

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

Example.

// assignment of strings, function assign () string s1 = "site"; string s2; string s3; char * ps = "site"; s3 = s1; // s3 = "site" s2.assign (s1); // s2 = "site" s2.assign (s1, 0, 4); // s2 = "best" s2.assign (ps, 8); // s2 = "bestprog"
9. Concatenation of strings. Append () function. Example

The append () function is used to concatenate strings. You can also use the operation to add lines ‘+’ , for example:

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

However, the append () function is good when you need to append 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 implementation, the function receives a link to a string object s which is added to the caller. In the second implementation, the function receives a pointer to a const char * string, which ends with the '\ 0' character.

Example. Demonstration of the append () function.

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

10. Inserting characters in a line. Insert () function. Example

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

The first version of the function allows you to insert the entire string s at the given start position of the calling line (calling object):

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

The second version of the function allows you to insert a part (insStart, num parameters) of string s at 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 - the string to be inserted into the calling string;
  • start - the position in the calling line from which to insert the string s;
  • insStart - the position in string s from which to insert;
  • num is the number of characters in string s to be inserted from position insStart.
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. Replace () function. Example

The replace () function replaces 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 implementation, the calling string is replaced with the string s. It is possible to set the position (start) and the number of characters (num) in the calling line, which must be replaced with the string s.

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

Example. Demonstration of 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" // replace characters, 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. Removal a given amount characters from the string. Erase () function. Example

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

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

  • index - index (position), starting from which you want to remove characters in the calling line;
  • num is the number of characters to be removed.

Example.

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

13. Search for a character in a string. Find () and rfind () functions. Examples of

In the string class, searching for a string in a substring can be done in two ways, which differ in the direction of the search:

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

The find () function prototype looks like this:

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

  • s - the substring that is searched for in the string, which causes this function... The function searches for the first occurrence of the string s. If the substring s is found in the string that called the given function, then the position of the first occurrence is returned. Otherwise -1 is returned;

The prototype for the rfind () function is:

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

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

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

// string type, find () function 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. Demonstration of the rfind () function.

// 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 // difference between find () and rfind () functions pos = s4.rfind (s3); // pos = 7 pos = s4.find (s3); // pos = 0
14. Comparison of parts of strings. Compare () function. Example

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

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

The compare () function prototype:

int compare (size_type start, size_type num, const string & s) const;
  • s - the string to compare with the calling string;
  • start - position (index) in string s, from which to start viewing the characters of the string for comparison;
  • num is the number of characters in string s to compare against the calling string.

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

Example... Demonstration of the compare () function:

// string type, compare () function 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 *). C_str () function. Example

To get a string that ends with a character ‘\0’ the function c_str () is used.

Function prototype:

const char * c_str () const;

The function is declared with the const modifier. This means that the function cannot modify the caller (string).

Example 1... Converting string to const char *.

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

Example 2.

The following demonstrates the translation of a string from string to the System :: String type for displaying it in a control of the Label type.

The modern C ++ standard defines a class with functions and properties (variables) for organizing work with strings (in the classical C language, there are no strings as such, there are only char arrays):

#include

#include

#include

To work with strings, you also need to connect the standard namespace:

Using namespace std;

Otherwise, you will have to specify the class descriptor std :: string instead of string everywhere.

Below is an example of a program that works with string (does not work in old C-compatible compilers!):

#include #include #include using namespace std; int main () (string s = "Test"; s.insert (1, "!"); cout<< s.c_str() << endl; string *s2 = new string("Hello"); s2->erase (s2-> end ()); cout<< s2->c_str (); cin.get (); return 0; )

The main features of the string class:

  • initialization with an array of characters (a string of built-in type) or another object of type string. The built-in type does not have the second option;
  • copying one line to another. For a built-in type, you have to use the strcpy () function;
  • access to individual characters of the string for reading and writing. In a built-in array, this is done using the operation of taking the index or indirect addressing using a pointer;
  • comparison of two strings for equality. For built-in types, functions of the strcmp () family are used;
  • concatenation (concatenation) of two strings, giving the result either as the third string, or instead of one of the original ones. For a built-in type, the strcat () function is used, however, to get the result in new line, it is necessary to sequentially use the strcpy () and strcat () functions, and also take care of memory allocation;
  • built-in means of determining the length of a string (member functions of the class size () and l ength ()). You can find out the length of a string of a built-in type only by computation using the strlen () function;
  • the ability to find out if a string is empty.

Let's take a closer look at these basic features.

Initializing strings when describing and line length(not including the terminating null terminator):

String st ("My string \ n"); cout<< "Длина " << st << ": " << st.size() << " символов, включая символ новой строки\n";

The string can be given and empty:

String st2;

To check whether is the line empty, you can compare its length with 0:

If (! St.size ()) // empty

or use the empty () method, returning true for an empty string and false for a non-empty string:

If (st.empty ()) // empty

The third form of string creation initializes an object of type string with another object of the same type:

String st3 (st);

String st3 is initialized with string st. How can we make sure that these strings match? Let's use the comparison operator (==):

If (st == st3) // initialization worked

How copy one line to another? With the usual assignment operation:

St2 = st3; // copy st3 to st2

For string concatenation use the addition operation (+) or the addition assignment operation (+ =). Let two lines be given:

String s1 ("hello,"); string s2 ("world \ n");

We can get the third line, consisting of the concatenation of the first two, like this:

String s3 = s1 + s2;

If we want to add s2 to the end of s1, we have to write:

S1 + = s2;

The addition operation can concatenate class objects string not only among themselves, but also with strings of built-in type. You can rewrite the above example so that special characters and punctuation marks are represented by the built-in char * type, and significant words are represented by string objects:

Const char * pc = ","; string s1 ("hello"); string s2 ("world"); string s3 = s1 + pc + s2 + "\ n"; cout<< endl << s3;

Expressions like these work because the compiler "knows" how to automatically convert objects of the built-in type to objects of the string class. A simple assignment of an inline string to a string object is also possible:

String s1; const char * pc = "a character array"; s1 = pc; // right

In this case, the inverse transformation does not work... Attempting to do the following initialization of a built-in type string will throw a compilation error:

Char * str = s1; // compilation error

To perform this conversion, you must explicitly call the member function c_str () ("C string"):

Const char * str = s1.c_str ();

The c_str () function returns a pointer to a character array containing the string of the string object as it would be in a built-in string type. The const keyword here prevents the "dangerous" in modern visual environments the possibility of directly modifying the contents of an object through a pointer.

TO individual characters an object of type string, like a built-in type, can be accessed using the operation of taking the index. For example, here's a snippet of code that replaces all dots with underscores:

String str ("www.disney.com"); int size = str.size (); for (int i = 0; i< size; i++) if (str[i] == ".") str[ i ] = "_"; cout << str;

Replace (str.begin (), str.end (), ".", "_");

True, not the replace method of the string class is used here, but the algorithm of the same name:

#include

Because the string object behaves like a container, other algorithms can be applied to it. This allows you to solve problems that are not directly solved by the functions of the string class.

Below is a brief description of the main operators and functions of the string class, links in the table lead to Russian-language descriptions on the Internet. For a more complete list of the capabilities of the string class, see, for example, Wikipedia or cplusplus.com.

Specifying characters in a string

operator =

assigns values ​​to a string

assign

assigns characters to a string

Access to individual symbols

at

getting the specified character checking if the index is out of bounds

operator

getting the specified character

front

getting the first character

back

get the last character

data

returns a pointer to the first character of the string

c_str

returns unmodifiable a C character array containing the characters in the string

Checking for line capacity

empty

checks if a string is empty

size
length

returns the number of characters in a string

max_size

returns the maximum number of characters

reserve

reserves space for storage

String operations

clear

clears the contents of the string

insert

inserting symbols

erase

delete characters

push_back

appending a character to the end of the line

pop_back

removes the last character

append

operator + =

appends characters to the end of the line

compare

compares two strings

replace

replaces every occurrence of the specified character

substr

returns a substring

copy

copies characters

resize

changes the number of characters stored

Allows the program to open data files in specified folders as if they were in the current folder. Called without parameters, the command append lists the linked directories.

Syntax

append [; ] [[disk: ]way[; ...]] [/ x:{on|off}] [/ path:{on|off}] [/ e]

Options

; Clears the list of folders specified in previous calls to append. [ disk: ]way Specifies the drive and folder that you want to attach to the current folder. If no drive is specified, the current drive is used by default. It is possible to specify several combinations [ disk: ]way separated by semicolons. / x:{on | off) Determines whether the MS-DOS subsystem will look for attached folders when executing programs. / x: on search for attached folders is in progress. / x: off the search for attached folders is not performed. / path:{on|off) Tells the program to search for files in the attached folders if the file names are specified in full. The default is / path: on... / e Writes the list of attached folders to the APPEND environment variable. This command line parameter can only be used the first time the command is invoked append after starting the system. /? Displays help on the command line.

Notes

  • Saving the list of attached folders

    Command line parameter / e commands append lets you assign the list of attached folders to an environment variable named APPEND. To do this, first use the command append with only command line parameter / e... Then re-use the command append by specifying the folders you want to attach. Options / e and [ disk: ]way cannot be used on the same command line.

  • Setting multiple attached folders

    To attach multiple folders, enter them separated by semicolons. When you call the command again append with parameters [ disk: ]way existing list of attached folders in command append will be replaced by a new one.

  • Using a parameter dir

    When using the command dir for listing files and subdirectories of a directory, filenames from attached folders are not displayed.

  • Resolving file name conflicts

    If the names of the files in the current and attached folders are the same, the files of the current folder are opened for the programs to work.

  • Command append and creating new files

    If a file is open in an attached folder, then the work with it is carried out in the same way as with the files of the current folder. If you save a file by creating a file with the same name, the new file is saved in the current folder, not in the attached folder. Command append used when working with data files that do not change or change without creating new copies. For example, when working with databases, new copies of files are usually not created. Text editors and processors usually save files by making new copies. To avoid incorrect work, do not use the command append with such programs.

  • Using a parameter / x: on with the team path

    If the parameter is set / x: on, programs located in attached folders can be launched simply by entering the program name in the command line. Usually the command path allows you to specify folders containing programs, but you do not need to use the command to specify attached folders containing programs path... The MS-DOS subsystem will find this program using the list of attached directories. This is because MS-DOS first looks for the executable file of the program in the current directory and then in the directories specified by the command.

  • Parameter reduction / x: on before / x

    It is possible to reduce the parameter / x: on before / x... To do this, enter the parameter / x: on the first time the command is invoked append after starting the system. Then you can switch between / x: on and / x: off.

  • Using a parameter / e with the team set

    Using the parameter / e with the team set, you can display a list of attached folders.

Examples of

To be able to open data files in programs from the B: \ Letters and A: \ Reports folders as from the current folder, enter:

append b: \ letters; a: \ reports

append b: \ letters; a: \ reports

For questions, discussions, comments, suggestions, etc., you can use forum section this site (registration required).

  • Announcement:

    Procedure Append (Var F: Text);

    Where:
    F is a text file variable.

  • Description:

    Opens an existing file to continue writing to the file.

  • Notes:

    The F parameter is a text file variable that must be associated with the external file using the Assign procedure call.

    Append opens an existing external file with the name specified in the file variable F. If an external file with the given name does not exist, an I / O error occurs. If F is already open, then it closes and reopens. The current file position is set to the end of the file.

    If the last 128-byte block of the file contains the character Ctrl + Z (character, with code 26), then the current file position is set so as to overwrite the first encountered Ctrl + Z in the block. Thus, text can be appended to a file that ends with Ctrl + Z.

    If F has been assigned, an empty name, such as Assign (F, ""), then after appending to Append, F refers to standard output (descriptor number = 1).

    After appending to Append, F becomes a read-only file, and the file position pointer is set to the end of the file.

    In (I-) mode, the IOResult function will return zero if the operation was successful, otherwise it will return a nonzero error code.

  • Example:

    (Sample program for Append procedure)
    Uses WinCrt;
    Var F: Text;
    Begin
    Assign (F, "TEST.TXT");
    ReWrite (F); (Create a new file)
    WriteLn (F, "Some text ;-)");

    Append (F); (Add data to the end of the file)
    WriteLn (F, "Some more text!");
    Close (F); (Close the file)
    End.