SUBSTR()

This is a member of the std::string class used to extract a portion of a string. It takes two arguments: the starting position (pos) and the number of characters to extract (len). If the length is not specified, it returns all characters from the starting position to the end of the string. The function returns a new std::string object containing the extracted substring and does not modify the original string. If the starting position is beyond the size of the string, substr() throws a std::out_of_range exception. This function is commonly used for tasks such as parsing, formatting, or manipulating text.

std::string std::string::substr(size_t pos = 0, size_t len = npos) const;

 * pos: The starting position of the substring (default is 0).
 * len: The number of characters to extract (default is std::string::npos, 
   meaning "until the end of the string").
#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    std::string sub = str.substr(7, 5);  // Extracts "world"
    std::cout << sub << std::endl;
    return 0;
}

Last updated