gogoWebsite

Common operations of std::string class

Updated to 16 days ago

std::string is a class in the C++ standard library that represents and manipulates strings. Use the std::string class to facilitate string creation, modification, connection, search, etc., and compared with traditional C-style string operations, std::string provides more convenience and security.

string assignment operation

Used to assign a string to another string object, including assigning using = and assigning() function.

  1. string assignment operation=:
std::string str1 = "Hello";  // Initialize with string literals
std::string str2;
str2 = str1;  // Assign the value of str1 to str2 using the assignment operator

  1. useassign()function:
std::string str1 = "Hello";  // Initialize with string literals
std::string str2;
str2.assign(str1);  // Use the assign() function to assign the value of str1 to str2

  1. Use another string to assign values:
std::string str1 = "Hello";  // Initialize with string literals
std::string str2 = str1;  // Assign values ​​using another string

  1. Assign values ​​using C-style strings:
const char* cstr = "Hello";  // C-style string
std::string str;
str = cstr;  // Assign values ​​using C-style strings

string access characters

Single characters in a string can be accessed through the subscript operator [], or the at() function can be accessed. You can also use the front() and back() functions to get the first and last characters of the string respectively.

  1. Use subscript operator[ ]
std::string str = "Hello";
char ch = str[0];  // Access the first character 'H'

  1. useat( )function:
std::string str = "Hello";
char ch = str.at(1);  // Access the second character 'e'

  1. usefront( )Functions andback( )function:
std::string str = "Hello";
char firstChar = str.front();  // Get the first character 'H'
char lastChar = str.back();    // Get the last character 'o'

string splicing operation

Use the plus operator + to splice multiple strings together. A single string cannot be spliced, and string objects can be spliced

  1. Use plus operator +
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + str2;  // Splice str1 and str2 to get "HelloWorld"

  1. use+=Operators are spliced ​​in-place:
std::string str1 = "Hello";
std::string str2 = "World";
str1 += str2;  // Splicing in place, str1 becomes "HelloWorld"

  1. Splice other types of data into strings:
std::string str = "The value is: ";
int value = 42;
str += std::to_string(value);  // Splice integers, the result is "The value is: 42"

//to_string: Convert numeric constants to strings, return value is the converted string

string insertion operation

You can use the insert() function to insert characters or substrings at a specified position.

  1. Insert string at the specified location:
std::string str = "Hello";
std::string insertStr = " World";
str.insert(5, insertStr);  // Insert "World" in position 5, and the result is "Hello World"

  1. Insert a string at the end of the string:
std::string str = "Hello";
std::string insertStr = " World";
str.insert(str.length(), insertStr);  // Insert "World" at the end, and the result is "Hello World"
//The first parameter of the insert() function is the position to be inserted. You can use () to represent the end position of the string.

string delete operation

Use the erase() function to delete characters or substrings in strings.

  1. Delete a single character:
std::string str = "Hello";
str.erase(3);  // Delete the character with position 3, and the result is "Helo"

  1. Delete a substring:
std::string str = "Hello World";
str.erase(6, 5);  // Delete 5 characters starting from position 6, and the result is "Hello"

  1. Clear the entire string:
std::string str = "Hello";
str.clear();  // Clear the string, the result is ""

Erase( ) and clear( ) functions modify the original string
The erase() function can also accept an iterator as a parameter to delete characters or substrings of the specified range, with higher flexibility

string search operation

Use the find() function to find the position of the substring in the string. There are other overloaded functions such as rfind() that can be found from behind to front, find_first_of() can be found any character in the character set, etc.

  1. Find the location of the substring:
std::string str = "Hello World";
std::string substr = "Wor";
size_t pos = str.find(substr);  // Find the location of the substring, the result is 6

//The find() function will return the position where the substring appears for the first time.  If a substring is found, it returns its starting position;
//If not found, return std::string::npos, i.e. a special constant.
  1. Find the location of the character:
std::string str = "Hello";
char ch = 'o';
size_t pos = str.find(ch);  // Find the position of the character, the result is 4

//size_t type represents the maximum length that any object in C can achieve
//Define as unsigned int on a 32-bit system, that is, a 32-bit unsigned integer.  Defined as unsigned long on a 64-bit system
  1. Check if the substring exists:
std::string str = "Hello World";
std::string substr = "Wor";
bool exists = (str.find(substr) != std::string::npos);  // Check whether the substring exists

std::string::npos:

It is a special constant in the C++ standard library, and its function is to indicate that no matching position was found in string operations. Its definition is as follows:

static const size_t npos = -1;

  • The value of std::string::npos is defined as -1 and is usually used as the return value for operations such as string search, comparison, and replacement.
  • When an operation cannot find or match a specific substring or character, the return value is std::string::npos.
  • When using the find() function for string search, if the target substring cannot be found, the find() function will return std::string::npos, indicating that no matching location was found.

string replacement operation

Use the replace() function to replace characters or substrings in strings.

  1. Replace substring:
std::string str = "Hello, World!";
std::string oldStr = "World";
std::string newStr = "GPT";
size_t pos = str.find(oldStr);  // Find the location of the substring to be replaced
while (pos != std::string::npos) {
    str.replace(pos, oldStr.length(), newStr);  // Perform replacement operation
    pos = str.find(oldStr, pos + newStr.length());  // Continue to find the next location to replace
}


  1. Replace a single character:

std::string str = "Hello, World!";
char oldChar = ',';  // Characters to be replaced
char newChar = '.';  // Replaced characters
std::replace(str.begin(), str.end(), oldChar, newChar);  // Use std::replace() to perform the replacement operation

std::replice( ):
Replace the character with the specified string with length len from the starting position pos:

tring& replace (size_t pos, size_t len, const string& str); 

string string length and capacity

Use the length() function to get the length of the string (number of characters), and use the size() function to get the length of the string
Use the capacity() function to get the capacity of a string

  1. String length:
std::string str = "Hello, World!";
int length = str.length();  // Or use ();

  1. String capacity:

String capacity represents the size of memory space allocated to store strings.

std::string str = "Hello, World!";
int capacity = str.capacity();

apacity() returns the size of the currently allocated memory space inside the string, which is not necessarily equal to the length of the string.
When the string exceeds the current capacity, the std::string class automatically reallocates larger memory space to accommodate longer strings.
If you want to manually reduce the memory space of a string, you can use the member function shrink_to_fit().

std::string str = "Hello, World!";
str.shrink_to_fit();  // Reduce the memory space of strings

The capacity of the string will be adjusted to match the length.

string determines empty string

Use the empty() function to determine whether the string is empty.

  1. Use empty() function:
std::string str = "Hello, World!";
if (str.empty()) {
    // The string is empty
} else {
    // String is not empty
}
//empty() function returns a boolean value, true if the string is empty, otherwise false.
  1. Use the length() or size() function for length comparison:
std::string str = "Hello, World!";
if (str.length() == 0) {
    // The string is empty
} else {
    // String is not empty
}

string comparison operation

Use the compare() function to compare the size relationship between two strings, and other overloaded functions such as <, >, <=, >=, etc. can be directly compared and judged.

  1. Use the equality operator == for equality comparison:
std::string str1 = "Hello";
std::string str2 = "World";

if (str1 == str2) {
    // string equal
} else {
    // Strings are not equal
}

//Return true if the two strings are exactly the same, otherwise return false.
  1. Use relational operators for size comparison:
std::string str1 = "Hello";
std::string str2 = "World";

if (str1 < str2) {
    // str1 is less than str2
} else if (str1 > str2) {
    // str1 is greater than str2
} else {
    // str1 equals str2
}

Return true if str1 is less than str2 in dictionary order; true if str1 is greater than str2; false if two strings are equal.

  1. Use the member function compare() to compare() for comparison:
std::string str1 = "Hello";
std::string str2 = "World";

int result = str1.compare(str2);
if (result < 0) {
    // str1 is less than str2
} else if (result > 0) {
    // str1 is greater than str2
} else {
    // str1 equals str2
}

string substring extraction

Use the substr() function to extract substrings from the original string.
The substr() function takes two parameters: the starting index of the substring to be extracted and the length of the substring.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    
    // Extract substrings starting from index position 7, with length 5
    std::string subStr = str.substr(7, 5);
    
    std::cout << subStr << std::endl;  // Output "World"
    
    return 0;
}

The first argument to the substr() function is the start index of the substring, counting from 0. The second parameter is the length of the substring. If the second parameter is omitted, all characters from the starting index to the end of the string are extracted.

string string conversion

You can use the c_str() function to convert a string object into a C-style string, and use stoi(), stof() and other functions to convert a string into an integer, a floating point number, etc.

  1. String to integer
  • usetd::stoiConvert:
std::string str = "123";
int num = std::stoi(str);

  • usestd::stolPerform long integer conversion, usestd::stollPerform long integer conversion.
  1. String to floating point number:
  • usestd::stofPerform single-precision floating point conversion usingstd::stod Row double precision floating point conversion
std::string str = "3.14";
float f = std::stof(str);
double d = std::stod(str);

  1. Integer/float-point to string:
  • usestd::to_string To convert integers into strings:
int num = 123;
std::string str = std::to_string(num);

  • use std::to_stringDo floating point conversion string:
float f = 3.14;
std::string str = std::to_string(f);

The above method will be thrown during the conversion processstd::invalid_argumentorstd::out_of_rangeException, if the string cannot be converted to the target type correctly, or is outside the scope of the target type.