Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if string ends with .txt

Tags:

c++

string

I am learning basic C++, and right now I have gotten a string from a user and I want to check if they typed the entire file name (including .txt) or not. I have the string, but how can I check if the string ends with ".txt" ?

string fileName;  cout << "Enter filename: \n"; cin >> fileName;  string txt = fileName.Right(4); 

The Right(int) method only works with CString, so the above code does not work. I want to use a regular string, if possible. Any ideas?

like image 439
Chronicle Avatar asked Dec 07 '13 20:12

Chronicle


People also ask

How do you check the end of a string?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

How do you check if string ends with one of the strings from a list?

The endswith() method returns True if a string ends with the specified suffix. If not, it returns False .

How do you check if a string ends with a pattern in Python?

The endswith() function returns True if a string ends with the specified suffix (case-sensitive), otherwise returns False. A tuple of string elements can also be passed to check for multiple options. If a string ends with any element of the tuple then the endswith() function returns True.


1 Answers

Unfortunately this useful function is not in the standard library. It is easy to write.

bool has_suffix(const std::string &str, const std::string &suffix) {     return str.size() >= suffix.size() &&            str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; } 
like image 135
Dietrich Epp Avatar answered Oct 02 '22 14:10

Dietrich Epp