Library contents

C++ std::string::compare

Check the end of a filename when listing receipts saved as PDFs.

A simple example

std::string::compare

  1. Start with "abc" and "bc"
  2. Do this Compare the ending
  3. Result Yes
The final two characters are exactly b and c.
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "abc";
    const std::string other = "bc";
    std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
    return 0;
}
Output
yes

Syntax

C++ syntax
label.size() >= 4 && label.compare(label.size() - 4, 4, ".pdf") == 0
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
./lesson

Find filenames with a receipt extension

A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.

From the programconst std::string label = "receipt.pdf"
Resultyes
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string label = "receipt.pdf";
    std::cout << ((label.size() >= 4 && label.compare(label.size() - 4, 4, ".pdf") == 0) ? "yes" : "no") << "\n";
    return 0;
}
Output
yes

The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.

Advertisements

Find a class roster

A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.

From the programconst std::string value = "class.csv"
Resultyes
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "class.csv";
    const std::string other = ".csv";
    std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
    return 0;
}
Output
yes

The final characters match the requested extension.

Exclude a backup export

A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.

From the programconst std::string value = "class.csv.old"
Resultno
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "class.csv.old";
    const std::string other = ".csv";
    std::cout << ((value.size() >= other.size() && value.compare(value.size() - other.size(), other.size(), other) == 0) ? "yes" : "no") << "\n";
    return 0;
}
Output
no

The final extension is .old.

What to watch for

A filename suffix describes a naming convention. It cannot verify the contents of a file.

Documentation for std::string::compare