C++ string ending check

Slapshot136

Divide et impera
Reaction score
471
Hi, i need some help checking the ending of a string, what would be the simplest way of doing that? (for a file type extension that may or may not be present)
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Code:
#include <string>
#include <iostream>

int findSuffix(std::string &str, std::string &pattern)
{
        int lstr = str.length();
        int lpat = pattern.length();

        if (lstr < lpat)
        {
                return 0;
        }

        return str.compare(lstr - lpat, lpat, pattern) == 0;
}

int main(int argv, char** argc)
{
        std::string a = "filename.txt";
        std::string b = "txt";

        std::cout << findSuffix(a, b) << std::endl;

        return 0;
}
 

Slapshot136

Divide et impera
Reaction score
471
ty, but im afraid i cant quite figure out what you did.. (my c++ knowledge is rather limited, but im learning) it seems to me like you compared the values of the end of the string and the ending, so allow me to be more specific. I want to check to see if there is a .htm or .html ending to a string, and if there is not, to add it. This part is what i currently have:

Code:
	    cin>>name;
		if (name == "*.htm" || name == "*.html" ) {
			name =  name;
		} else {
			name =  name + ".html";
		}

where * would be the rest of the file name.. (yes i know that it dosent work.. )
 
Reaction score
333
Try something like this:

Code:
std::string getFileExt(const std::string& fname) {
    size_t lastdot = fname.find_last_of('.');
    return (lastdot != std::string::npos) ? fname.substr(lastdot+1) : "";
}

It will return the file extension or "" if there is no extension.
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
I want to check to see if there is a .htm or .html ending to a string, and if there is not, to add it.

Code:
cin >> name;

if (!findSuffix(name, ".htm") && !findSuffix(name, ".html"))
{
  name =  name + ".html";
}
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top