C++ std::string::substr
Extract the first three characters of an ASCII department identifier.
A simple example
std::string::substr
- Start with "abc"
- Do this Take the first two characters
- Result "ab"
#include <iostream>
#include <string>
int main() {
const std::string value = "abc";
std::cout << (value.substr(0, 2)) << "\n";
return 0;
}
ab
Syntax
value.substr(0, 3)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonRead a department on a semester timetable
A semester timetable stores its department field inside a larger record. Read the designated portion without bringing along the separator or the room information that follows it.
#include <iostream>
#include <string>
int main() {
const std::string value = "BIO-204";
std::cout << (value.substr(0, 3)) << "\n";
return 0;
}
BIO
The first three letters identify the department.
Read the carrier code from a parcel
A structured code contains a department, room or other routing field inside a longer label. Extract the exact portion needed by the receiving system and verify which boundary is excluded.
#include <iostream>
#include <string>
int main() {
const std::string value = "AIR:482";
std::cout << (value.substr(0, 3)) << "\n";
return 0;
}
AIR
The colon and serial number lie outside the selected range.
Read a parcel sorting code
The depot scans a parcel marked NC-17. The printer needs the two-letter prefix that comes before the separator. Which letters should it print?
What to watch for
A length and an exclusive end index can look alike when starting at zero. Check the API before using a nonzero starting position.