Use the text information while working with databases, files, for receiving and sending messages, It is an integral part of every programmer.
Strings are used, for internal purposes (testing and debugging code), and to solve common problems, data to the client, GUI design. For this reason you should pay special attention to, how to construct a string in C ++, how to work with their basic operation and the methods of processing objects such as string faster, or more appropriately in a given situation.
Strings in C ++ can be a character arrays char – This built-in type, which has been used in C. Either instances of the class string, which is included in the standard C ++ library. It should be noted, that when you create an object of this type, we almost get a dynamically changing array, i.e.. the, that there is no need to set the initial size, because they can change the course of work with the essence.
In the first case the string is placed in memory, an array. A pointer typechar It is accessed. This approach is fraught with errors and is quite complex, It implemented as low.
class Objects string facilitate the work, through them, you can get access to the standard string operations. They belong to a namespace stl (Standard Template Library). For further use of the standard C library, you must connect the header file:
1 | #include <cstring> |
The simplest example of using a variable of type string will be removing it on the screen. But complicate the task and try, to start, considered a string value, and then operate it.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <string> using namespace std; int main() { string myString; // создаем переменную, в которую поместим строку cout << "What is your name? "; getline(cin, myString); // считываем введенную строку cout << "Hey, " << myString << "! \n"; // выводим значение переменной на экран } |
Methodgetline() It enables read data from streamcin, and burn them in the variable, which is indicated after the decimal point.
When, when you need to initialize a variable when it is created, you should use the following syntax:
1 | string oneMoreString = "Here is my new string!"; |
Consider the basic methods of the class string, that allow you to modify strings and receive information about their parameters.
Two methods can be used to obtain the string length. One of them size() other length(). Both methods return a numerical number of characters. But it should be noted, that the numbering of elements in the array string still begins with 0.
Listing for checking:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <iostream> #include <string> using namespace std; int main() { string myString; cout << "What is your name? "; getline(cin, myString); cout << "Hey, " << myString << "! \n"; cout << "Size is " << myString.size() << "\n"; cout << "Length is " << myString.length() << "\n"; } |
Next we see, Both methods return the same values.
To check for the presence of a string variable data it uses function empty(), which returns a boolean value ( 0 if false or 1 if true). This operation is useful, when you need to protect yourself against data loss.
To reset the string variable method is usedclear(). As a result, after executing myString.size() return 0, andmyString.empty() – value true, i.e.. 1.
Code Listing for checking functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <iostream> #include <string> using namespace std; int main() { string myString = "Not a bug, but a feature!"; cout << "Is empty? " << myString.empty() << "\n"; cout << "Size is " << myString.size() << "\n"; cout << "Clear it all! \n"; myString.clear(); // удаляем данные cout << "Is empty now? " << myString.empty() << "\n"; cout << "Size is " << myString.size() << "\n"; } |
Now consider the less trivial operations, that will save time and effort of programmers, as well as avoiding the use of massive loops to iterate over each of the string array.
Functionpush_back (char) It allows you to add to the end of the current line type any character char. When this, we do not need a restore of the new string value, the old variable will simply be modified.
Loop string It allows you to manipulate two strings at the same time, writing values from one to another. For this purpose, the subject line should call the methodinsert (int startInResultString, string from, int startInSourceString, int amount). WherestartInResultString – cell in the row starting position, in which to record the new data, i.e.. the new values will be placed from this index.
lowercase variablefrom – is a string from which data are taken, All further parameters are particular to it. The initial value of the index from which to start copying data indicatedstartInSourceString. Total symbols, that will be copied from the stringfromindicatedamount, counting is performed starting with the start index.
Code Listing will allow better understand the function of the input parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> #include <string> using namespace std; int main() { string myString1 = "Not a bug, But a feature!"; string myString2 = " said a developer."; cout << myString1 << "\n"; cout << myString2 << "\n"; myString1.insert(10, myString2, 0, 20); cout << myString1; } |
It was not all dismantled, but the most frequently-used functions for working with String objects. class advantage string It is the ease of use and support a large number of methods. Nevertheless, string objects are handled slowly. In some cases, it can happen, data loss or break the integrity of the string, which then can not be any way to bring in to check visually.
Experiment – Create an object of class string and call its methods on-line. Try to understand yourself, what they do and how they work. In many textbooks offered independently write your own (certainly tamed) class for working with strings. It's easy and you will understand perfectly the same time, How is the real class string. We will prepare for you some tasks, to secure this material.
Be sure to watch the video on the class (author Dennis Markov):
Video on how to create your own String class will help you figure it out, how everything works:
Good article, It may be the best in the entire series of articles – on the balance of detail and simplicity.
Just do not understand, why everywhere in the text of a class called String (with a capital), even if in the examples it is always used as a string (lower case). If you write the code String, then immediately get a rough syntax error.
Another good thing to mention, even casual (or a separate topic in the course of, “use string”?):
1. that of the string is always possible “extract” the more familiar idea char * (in the style of C) by c_str():
string s = “xxx”;
char *c = s.c_str();
2. a + = overdetermined operations and + to string, as the string concatenation:
string h = “Hello “, w = “world”;
cout << h + w << endl;
h += w;
cout << h << endl;
3. of a whole large group of methods, presentation of lines for the image of numeric values:
string d( "123" ), f( "1.23" );
long i = d.stoul();
float z = d.stof();
And last … comment:
> Both methods return a numerical number of characters.
length() and size() not return the number of characters, and the number of bytes in the string contents. For ASCII (English) characters – It is the same. But for Russian (and other languages) – no, and it depends on the encoding used.
string priv( "привет!" );
, whichever, in which the editor and what coding are working with the program code.cout << priv.size( ) << " | " << priv.length( );
The exact values are not important… But it is important to know, that length() and size() for the Russian strings do not provide the estimated number of characters, that may give rise to errors being found difficult!
Oleg, thanks for the complement to the article.
… I ate, filth, a few strings of the example!
But it should be understood, that the length “Hi!” is equal to 13.
#include
#include
using namespace std;
int main()
{
string myString; // create a variable, in which to put the string
cout << "What is your name? ";
getline(cin, myString); // We read the input line
cout << "Hey, " << myString << "! \n"; // We derive the value of the variable on the screen
}
I somehow getline(cin, myString); not robit
Sorry, that is not
hydc8j