C++ Programming/Code/IO/Streams/string

The string class
The string class is a part of the C++ standard library, used for convenient manipulation of sequences of characters, to replace the static, unsafe C method of handling strings. To use the string class in a program, the header must be included. The standard library string class can be accessed through the std namespace.

The basic template class is  and its standard specializations are   and.

Basic usage
Declaring a std string is done by using one of these two methods:

Text I/O
This section will deal only with keyboard and text input. There are many other inputs that can be read (mouse movements and button clicks, etc), but these will not be covered in this section, even reading the special keys of the keyboard will be excluded.

Perhaps the most basic use of the string class is for reading text from the user and writing it to the screen. In the header file iostream, C++ defines an object named cin that handles input in much the same way that cout handles output.

The >> operator will cause the execution to stop and will wait for the user to type something. If the user types a valid integer, it will be converted into an integer value and stored in x.

If the user types something other than an integer, the compiler will not report an error. Instead, it leaves the old content (a "random" meaningless value) in x and continues.

This can then be extended into the following program:

Although a string may hold a sequence containing any character—including spaces and nulls—when reading into a string using cin and the extraction operator (>>) only the characters before the first space will be stored. Alternatively, if an entire line of text is desired, the getline function may be used:

Getting user input
Fortunately, there is a way to check and see if an input statement succeeds. We can invoke the good function on cin to check what is called the stream state. good returns a bool: if true, then the last input statement succeeded. If not, we know that some previous operation failed, and also that the next operation will fail.

Thus, getting input from the user might look like this:

cin can also be used to input a string:

As with the scanf function from the Standard C Library, this statement only takes the first word of input, and leaves the rest for the next input statement. So, if you run this program and type your full name, it will only output your first name.

You may also notice the >> operator doesn't handle errors as expected (for example, if you accidentally typed your name in a prompt for a number.) Because of these issues, it may be more suitable to read a line of text, and using the line for input — this is performed using the function called getline.

The first argument to getline is cin, which is where the input is coming from. The second argument is the name of the string variable where you want the result to be stored.

getline reads the entire line until the user hits Return or Enter. This is useful for inputting strings that contain spaces.

In fact, getline is generally useful for getting input of any kind. For example, if you wanted the user to type an integer, you could input a string and then check to see if it is a valid integer. If so, you can convert it to an integer value. If not, you can print an error message and ask the user to try again.

To convert a string to an integer you can use the strtol function defined in the header file cstdlib. (Note that the older function atoi is less safe than strtol, as well as being less capable.)

If you still need the features of the >> operator, you will need to create a string stream as available from &lt;sstream&gt;. The use of this stream will be discussed in a later chapter.

More advanced string manipulation
We will be using this dummy string for some of our examples.

This invokes the default constructor with a  argument. Default constructor creates a string which contains nothing, i.e. no characters, not even a  (however std::string is not null terminated).

Will trigger the copy constructor. knows enough to make a deep copy of the characters it stores.

This will copy strings using assignment operator. Effect of this code is same as using copy constructor in example above.

Size
So for example one might do:

The methods  and   both return the size of the string object. There is no apparent difference. Remember that the last character in the string is  and not. Like in C-style strings, and arrays in general,  starts counting from 0.

I/O
The shift operators ( and  ) have been overloaded so you can perform I/O operations on   and   objects, most notably ,  , and filestreams. Thus you could just do console I/O like this:

Alternatively, if you want to read entire lines at a time, use. Note that this is not a member function. will retrieve characters from input stream  and assign them to   until   is reached or   is encountered. will reset the input string before appending data to it. can be set to any  value and acts as a general delimiter. Here is some example usage:

Because of the way  works (i.e. it returns the input stream), you can nest multiple   calls to get multiple strings; however this may significantly reduce readability.

Operators
in s can be accessed directly using the overloaded subscript  operator, like in   arrays:

prints "Hl".

supports casting from the older C string type. You can also assign or append a simple  to a string. Assigning a  to a   is as simple as

If you want to do it character by character, you can also use

Not surprisingly,  and   are also defined! You can append another, a   or a   to any string.

The comparison operators  all perform comparison operations on strings, similar to the C strcmp function. These return a true/false value.

Searching strings
You can use the  member function to find the first occurrence of a string inside another. will look for  inside   starting from position   and return the position of the first occurrence of the. For example:

Will simply print "4" which is the index of the first occurrence of "o" in. If we want the "o" in "World", we need to modify  to point past the first occurrence. would return 4, while  would give 7. If the substring isn't found,  returns  .This simple code searches a string for all occurrences of "wiki" and prints their positions:

The function  works similarly, except it returns the last occurrence of the passed string.

Inserting/erasing
You can use the  member function to insert another string into a string. For example:

Would return Hello Human World!

You can use  to remove a substring from a string. For example: Would return Hello!

You can use  to extract a substring from a string. For example: Would return World.

Backwards compatibility
For backwards compatibility with C/C++ functions which only accept  parameters, you can use the member functions   and   to return a temporary   string you can pass to a function. The difference between these two functions is that  returns a null-terminated string while   does not necessarily return a null-terminated string. So, if your legacy function requires a null-terminated string, use, otherwise use   (and presumably pass the length of the string in as well).

String Concatenation
Strings can be concatenated(appended) together by simply using the + operator Output here will be "Hello World"

Appending Strings
Another thing to note is that instead of the + operator or concatenation, the  class member function can be used to concatenate one string to another. The  object is permitted to be a string object or a C-string. This will add the string in the parenthesis to the string which is calling.

It should also be noted that the append function can be used to append a string at a specific character location in the string. If a programmer puts,   number of characters from position   in string   will be appended to the end of. For example, in the following code, there are two strings. 5 characters from the second string, starting with position 8 of  will be appended to the end of the first string,.

The code above will append the word  to the end of the first string, and then print   on the screen.

String Conversion to signed integer
Sometimes we want to convert strings into numbers. To do so we can use stoi function which takes a string as an argument and returns the value. To convert these strings to a number we save the stoi of the string variable in an integer variable. Output will be: Before stoi string :12023 and after stoi int: 12023 Before stoi string :1 and after stoi int: 1 Before stoi string :1232 and after stoi int: 1232

Integer Conversion to String
If we instead want to do the opposite and convert an integer to a string, we can use the to_string function, which takes an integer as an argument and returns the integer as a string. To convert this integer to a string, we call the to_string function. The integer variable is passed into the function as an argument. The function will then return that integer as a string, which can then be assigned to a string variable. Output will be: Before to_string int:12023 and after to_string string:12023

String Formatting
Strings can only be appended to other strings, but not to numbers or other datatypes, so something like  would not result in a string with the content. To convert other datatypes into string there exist the class, found in the include file. acts exactly like, the only difference is that the output doesn't go to the current standard output as provided by the operating system, but into an internal buffer, that buffer can be converted into a   via the   method.