Skip to content

string

What is string

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

Why use string

In C, string operations are provided but can only be implemented using character arrays. string, on the other hand, is a simple class that is easy to use and widely adopted in OI competitions. Compared to other STL containers, string has excellent constant factors, essentially on par with character arrays.

string can dynamically allocate memory

Like many STL containers, string can dynamically allocate memory, allowing us to directly use std::cin for input, though it is relatively slow. This also frees us from worrying about memory management.

string overloads addition and comparison operators

The addition operator for string can directly concatenate two strings or a string and a character. Similar to std::vector, string overloads comparison operators, which compare strings lexicographically. Thus, we can directly call std::sort to sort multiple strings.

Usage

Below are the basic operations of string. For details, refer to the C++ documentation.

Declaration

1
std::string s;

Convert to char array

In C, many string functions take char pointers as parameters. For convenience, string has two member functions that convert itself to a char pointer—data()/c_str() (they are almost identical, but it's better to use c_str() because it guarantees a null terminator at the end, while data() does not). For example:

1
2
3
printf("%s", s);          // Compilation error
printf("%s", s.data());   // Compiles, but undefined behavior
printf("%s", s.c_str());  // Guaranteed to output correctly

Get length

Several functions can return the length of a string:

1
2
3
printf("Length of s is %zu", s.size());
printf("Length of s is %zu", s.length());
printf("Length of s is %zu", strlen(s.c_str()));

Complexity of these functions

The complexity of strlen() is always linear with respect to the string length.

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

Warning

The return types of these three functions (and the find function mentioned below) are size_t (unsigned long). Therefore, these return values should not be directly compared or operated with negative numbers. It is recommended to cast them when necessary.

Find the first occurrence of a character (string)

The find(str,pos) function can be used to find the first occurrence of a character/string in the string after position pos (inclusive). If pos is not provided, it defaults to 0. If not found, it returns string::npos (defined as -1, but its type is still size_t/unsigned long).

Example:

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

Output:

1
2
3
4
5
Character I first appears at position 1 in s
Character a first appears at position 18446744073709551615 in s // This is size_t(-1), the exact value depends on the platform.
Character a first appears at position -1 in s // Cast to int, it outputs -1 normally
String t first appears at position 0 in s
Starting from position pos in s, string u first appears at position 6

Extract substring

The substr(pos, len) function returns a string consisting of at most len characters starting from position pos (if the suffix starting from pos is shorter than len, the suffix is taken).

Example:

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

Output:

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

Insert/delete characters (strings)

insert(index,count,ch) and insert(index,str) are common insertion functions. They insert the character ch count times consecutively at index, and insert the string str at index, respectively.

The erase(index,count) function deletes count characters starting from position index (inclusive). If count is not provided, it deletes all characters from index onward.

Example:

1
2
3
4
5
6
7
8
9
string s = "OI Wiki", t = " Wiki";
char u = '!';
s.erase(2);
printf("After deleting all characters from the third position of string s, the resulting string is %s\n", s.c_str());
s.insert(2, t);
printf("After inserting string t at the third position of string s, the resulting string is %s\n", s.c_str());
s.insert(7, 3, u);
printf("After inserting string u three times consecutively at the eighth position of string s, the resulting string is %s",
       s.c_str());

Output:

1
2
3
After deleting all characters from the third position of string s, the resulting string is OI
After inserting string t at the third position of string s, the resulting string is OI Wiki
After inserting string u three times consecutively at the eighth position of string s, the resulting string is OI Wiki!!!

Replace characters (strings)

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

Example:

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

Output:

1
2
After replacing characters 3~7 of string s with an empty string, the resulting string is OI
After replacing the first two characters of string s with NOI, the resulting string is NOI