string

What is string?

std::string is a class provided in the standard library <string> (note that this is not the C library <string.h>); it is essentially an alias for std::basic_string<char>.

Why use string?

The C language provides string operations, but strings can only be implemented through character arrays. string, on the other hand, is a simple class that is easy to use and is widely used in OI competitions. Moreover, compared with other STL containers, the constant factors of string are very good—basically comparable to those of character arrays.

string can allocate space dynamically

Like many STL containers, string can allocate space dynamically. This allows us to use std::cin directly for input, although it is likewise slower. It also means that we do not need to worry about memory.

string overloads the addition and comparison operators

The addition operator of string can directly concatenate two strings or a string and a character. Like std::vector, string overloads the comparison operators and compares in lexicographical order, so we can directly call std::sort to sort several strings.

Usage

The basic operations of string are introduced below; see the C++ documentation for details.

Declaration

std::string s;

Convert to a char array

There are also many string functions in C, but their parameters are all of char-pointer type. For convenient use, string has two member functions that convert itself to a char pointer—data()/c_str() (they are almost the same, but c_str() is preferable because c_str() guarantees a null character at the end, whereas data() does not), for example:

printf("%s", s);          // Compilation error
printf("%s", s.data());   // Compiles, but this is undefined behavior
printf("%s", s.c_str());  // Always outputs correctly

Get the length

Many functions can return the length of a string:

printf("The length of s is %zu", s.size());
printf("The length of s is %zu", s.length());
printf("The length of s is %zu", strlen(s.c_str()));
Complexity of these functions

The complexity of strlen() is necessarily linear in the length of the string.

The complexity of size() and length() was unspecified in C++98 and specified as constant in C++11. However, on common compilers, the complexity of these two functions is constant even in C++98.

Warning

The return types of these three functions (as well as the find function mentioned below) are all size_t (unsigned long). Therefore, these return values cannot be compared or operated on directly with negative numbers; an explicit conversion is recommended when needed.

Find the first occurrence of a character (string)

The find(str,pos) function can find the first occurrence of a character/string in a string at or after pos (if pos is not passed, it defaults to 0). If it does not occur, it returns string::npos (defined as -1, but whose type is still size_t/unsigned long).

Example:

string s = "OI Wiki", t = "OI", u = "i";
int pos = 5;
printf("Character I first appears in s at position %lu\n", s.find('I'));
printf("Character a first appears in s at position %lu\n", s.find('a'));
printf("Character a first appears in s at position %d\n", s.find('a'));
printf("String t first appears in s at position %lu\n", s.find(t));
printf("Starting at pos in s, string u first appears at position %lu", s.find(u, pos));

Output:

Character I first appears in s at position 1
Character a first appears in s at position 18446744073709551615 // This is size_t(-1); the exact value depends on the platform.
Character a first appears in s at position -1 // After conversion to int, -1 is output normally.
String t first appears in s at position 0
Starting at pos in s, string u first appears at position 6

Extract a substring

The substr(pos, len) function starts at pos and returns at most len characters as a string (if the suffix starting at pos is shorter than len, it extracts that suffix).

Example:

string s = "OI Wiki", t = "OI";
printf("The substring of at most three characters starting at the fourth character of s is %s\n",
       s.substr(3, 3).c_str());
printf("The substring of at most three characters starting at the second character of t is %s",
       t.substr(1, 3).c_str());

Output:

The substring of at most three characters starting at the fourth character of s is Wik
The substring of at most three characters starting at the second character of t is I

Insert/delete characters (strings)

insert(index,count,ch) and insert(index,str) are common insertion functions. They respectively mean: at index, insert count copies of the string ch consecutively, and insert str.

The erase(index,count) function deletes the substring starting at index (inclusive) and containing count characters. If count is not passed, it deletes the characters at and after index.

Example:

string s = "OI Wiki", t = " Wiki";
char u = '!';
s.erase(2);
printf("After deleting every character of s from the third character onward, the result is %s\n", s.c_str());
s.insert(2, t);
printf("After inserting t at the third character of s, the result is %s\n", s.c_str());
s.insert(7, 3, u);
printf("After inserting u three times at the eighth character of s, the result is %s",
       s.c_str());

Output:

After deleting every character of s from the third character onward, the result is OI
After inserting t at the third character of s, the result is OI Wiki
After inserting u three times at the eighth character of s, the result is OI Wiki!!!

Replace characters (strings)

replace(pos,count,str) and replace(first,last,str) are common replacement functions. They respectively mean replacing the substring starting at pos and containing count characters with str, and replacing the substring from first (inclusive) to last (exclusive) with str, where first and last are iterators.

Example:

string s = "OI Wiki";
s.replace(2, 5, "");
printf("After replacing characters 3 through 7 of s with an empty string, the result is %s\n", s.c_str());
s.replace(s.begin(), s.begin() + 2, "NOI");
printf("After replacing the first two characters of s with NOI, the result is %s", s.c_str());

Output:

After replacing characters 3 through 7 of s with an empty string, the result is OI
After replacing the first two characters of s with NOI, the result is NOI

This content comes from OI Wiki: string. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.