Text and Parsing Utilities
Extract Prefix
substr copies part of a string, which is useful when a record has a fixed prefix.
substr
`substr(start, count)` returns a new string starting at `start` with at most `count` characters.
prefix
A prefix is the leading part of a string.
Extract Prefix
extract_prefix.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <string>
int main() {
int width = 3;
std::string code = "INV-2048";
std::string prefix = code.substr(0, width);
int size = static_cast<int>(prefix.size());
std::cout << "prefix=" << prefix << std::endl;
std::cout << "size=" << size << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int width = 2;
std::string code = "INV-2048";
std::string prefix = code.substr(0, width);
int size = static_cast<int>(prefix.size());
std::cout << "prefix=" << prefix << std::endl;
std::cout << "size=" << size << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
int width = 5;
std::string code = "INV-2048";
std::string prefix = code.substr(0, width);
int size = static_cast<int>(prefix.size());
std::cout << "prefix=" << prefix << std::endl;
std::cout << "size=" << size << std::endl;
return 0;
}
width ← 3, code ← INV-2048, prefix ← INV, size ← 3
4int main() {5 int width→ 3 = 3; //@width=2, 567 std::string code→ INV-2048 = "INV-2048";8 std::string prefix→ INV = codeINV-2048.substr(0, width3);9 int size→ 3 = static_cast<int>(prefixINV.size());1011 std::cout << "prefix=" << prefixINV << std::endl;12 std::cout << "size=" << size3 << std::endl;13 return 0;14}outputprefix=INV size=3
width ← 2, code ← INV-2048, prefix ← IN, size ← 2
4int main() {5 int width→ 2 = 2;67 std::string code→ INV-2048 = "INV-2048";8 std::string prefix→ IN = codeINV-2048.substr(0, width2);9 int size→ 2 = static_cast<int>(prefixIN.size());1011 std::cout << "prefix=" << prefixIN << std::endl;12 std::cout << "size=" << size2 << std::endl;13 return 0;14}outputprefix=IN size=2
width ← 5, code ← INV-2048, prefix ← INV-2, size ← 5
4int main() {5 int width→ 5 = 5;67 std::string code→ INV-2048 = "INV-2048";8 std::string prefix→ INV-2 = codeINV-2048.substr(0, width5);9 int size→ 5 = static_cast<int>(prefixINV-2.size());1011 std::cout << "prefix=" << prefixINV-2 << std::endl;12 std::cout << "size=" << size5 << std::endl;13 return 0;14}outputprefix=INV-2 size=5