Substring
- C++ course
- Beginner
- Lesson 33/116
- 5 min
Learn to take part of a string with .substr().
The substr method
To take only part of a string you use the substr method. It is called as s.substr(start, len); start is the starting index and len is how many characters to take. Indices are zero-based.
For example std::string s = "Computer"; s.substr(0, 4) returns "Comp". If you omit the second parameter, s.substr(start) returns everything from the start index to the end of the string.
Single-parameter substr
If you pass only the start index to substr, you get the rest of the string from that index on. std::string s = "Programming"; s.substr(7) returns "ming".
This short form is handy for separating file extensions or suffixes. Negative indices are not supported in C++; the index must be between 0 and s.length().
Practice Print the first four characters
The text variable is set to "Computer". Take the first four characters with text.substr(0, 4) into the part variable and print it with std::cout. The output must be Comp.
Starter code
#include <iostream>
#include <string>
int main() {
std::string text = "Computer";
// Take the first four characters into part and print
return 0;
}Sample solution
#include <iostream>
#include <string>
int main() {
std::string text = "Computer";
std::string part = text.substr(0, 4);
std::cout << part << std::endl;
return 0;
}Expected output
Comp
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does std::string s = "Computer"; s.substr(4, 3) return?
std::string s = "Computer";
s.substr(4, 3)- "Com"
- "ute" Correct answer
- "Comp"
- "uter"
Explanation: From index 4 take 3 characters: "ute".
2 Write the substr start parameter
std::string s = "Welcome";
std::string part = s.substr(____, 3);
std::string s = "Welcome";
std::string part = s.substr(0, 3);
Explanation: substr(0, 3) returns the first three characters.
3 Match each substr call to its result
| Term | Meaning |
|---|---|
s.substr(0, 3) on "Welcome" |
"Wel" |
s.substr(3) on "Welcome" |
"come" |
s.substr(0, 1) on "Welcome" |
"W" |
s.substr(4, 2) on "Welcome" |
"om" |