C++ std::string ends_with() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::string

Definition

In C++, std::string::ends_with() tells you whether the string ends with a given suffix (C++20).

Include <string>.

This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.

Syntax

Pass a suffix string or character.

C++
bool ok = name.ends_with(".cpp");
bool bang = s.ends_with('!');
CallWhat it does
s.ends_with(suffix)True if s ends with suffix.
s.ends_with(ch)True if the last character is ch.

Handy for file extension checks.

Library declarations
C++
bool ends_with(string_view sv) const noexcept; // C++20
bool ends_with(char ch) const noexcept;
bool ends_with(const char* s) const;

Parameters

ParameterDescription
suffixExpected ending text or character.

Return Value

Return ValueDescription
boolTrue when the suffix matches.

C++ Examples

Example 1 — Basic ends_with

Check a .cpp extension.

C++
#include <iostream>
#include <string>

int main() {
    std::string file = "main.cpp";
    std::cout << std::boolalpha << file.ends_with(".cpp") << '\\n';
    return 0;
}

How It Works

  1. The name ends with .cpp.
  2. ends_with returns true.
  3. Common filter for source files.

Example 2 — Ends With Char

Check a trailing newline-like mark.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = "line!";
    std::cout << std::boolalpha << s.ends_with('!') << '\\n';
    return 0;
}

How It Works

  1. Last character is '!'.
  2. Character overload matches.
  3. Returns true.

Example 3 — Suffix Missing

Non-matching ending.

C++
#include <iostream>
#include <string>

int main() {
    std::string s = "report.txt";
    std::cout << std::boolalpha << s.ends_with(".md") << '\\n';
    return 0;
}

How It Works

  1. Actual suffix is .txt.
  2. Check for .md fails.
  3. Result is false.

Frequently Asked Questions

Returns true if the string ends with the given suffix.
C++20.
Yes—ends_with(".png") style checks.
Yes. ".CPP" will not match ".cpp".
Compare the last suffix.size() characters with compare or substr.

Next: erase()

Keep going through the string functions. Remove characters by index, count, or iterator range.

erase() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful