How to Use substr in C++: Syntax and Examples
In C++, use the
substr method of the std::string class to extract a substring. Call it like str.substr(start, length), where start is the starting index and length is how many characters to take.Syntax
The substr method extracts a part of a string starting from a given position and for a specified length.
- start: The zero-based index where extraction begins.
- length: (Optional) Number of characters to extract. If omitted, extracts till the end of the string.
cpp
string substr (size_t start = 0, size_t length = npos) const;
Example
This example shows how to extract substrings from a string using substr. It prints parts of the original string based on start position and length.
cpp
#include <iostream> #include <string> int main() { std::string text = "Hello, world!"; // Extract "Hello" std::string part1 = text.substr(0, 5); // Extract "world" std::string part2 = text.substr(7, 5); // Extract from index 7 to end "world!" std::string part3 = text.substr(7); std::cout << part1 << std::endl; std::cout << part2 << std::endl; std::cout << part3 << std::endl; return 0; }
Output
Hello
world
world!
Common Pitfalls
Common mistakes when using substr include:
- Using a
startindex greater than the string length causes anout_of_rangeexception. - Requesting a
lengththat extends beyond the string end does not cause error; it returns up to the string's end. - Remember that string indices start at 0, so the first character is at position 0.
cpp
#include <iostream> #include <string> int main() { std::string s = "Example"; // Wrong: start index too large try { std::string wrong = s.substr(10, 2); // throws std::out_of_range } catch (const std::out_of_range& e) { std::cout << "Caught out_of_range error: " << e.what() << std::endl; } // Right: check length before calling substr if (s.size() > 10) { std::string safe = s.substr(10, 2); } else { std::cout << "Start index too large, skipping substr call." << std::endl; } return 0; }
Output
Caught out_of_range error: basic_string::substr
Quick Reference
Summary tips for using substr:
- Use
substr(start, length)to get a substring. - If
lengthis omitted, substring goes to the end. - Check that
startis within string length to avoid exceptions. - Indices start at 0.
Key Takeaways
Use std::string::substr(start, length) to extract parts of a string in C++.
The start index must be within the string length to avoid exceptions.
If length is omitted, substr returns from start to the string's end.
String indices start at zero, so count carefully.
Always handle or check for out_of_range exceptions when using substr.