C++ substr() Guide: Extract Substrings Safely with Examples
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
std::string::substr(pos, count) returns a new std::string containing characters copied from the original starting at index pos. The first argument is zero-based; the second is optional and limits how many characters to copy. If count is omitted, or if it is larger than the number of characters remaining, the substring extends to the end of the source string. The original string is not modified, so substr() is useful for parsing, tokenizing, and displaying fragments.
The example creates Hello, C++ substr!, then extracts Hello, C++, and substr! using different position and length combinations. The program prints each result, demonstrating that count is clamped to the available characters. It also shows that a starting position greater than size() throws std::out_of_range, which is caught and reported. Positions are zero-based, while size() returns the number of characters. Input is a source std::string plus optional position and count; output is a newly allocated substring. Time complexity is O(count) because up to count characters are copied, with O(count) extra space for the returned string. Invalid positions require exception handling if input is untrusted. Always validate user-supplied offsets, or use size() to check bounds before calling it. Use substr() when you need a copy; use std::string_view for non-owning slices.