Code semantics

I'm just curious which way of writing this code looks better to you. It's a simple function to determine if a string ends in ".txt", and I rewrote the function to reduce the size of the conditions in my if statement. Now I'm curious what your opinion is, what's worse; making a very long if statement, or the conversions I've done to shorten it...
1
2
3
4
5
6
7
8
bool isTxt(string fileName)
{
    if(fileName[fileName.size() - 1] == 't' && fileName[fileName.size() - 2] == 'x' && fileName[fileName.size() - 3] == 't' && fileName[fileName.size() - 4] == '.')
    {
        return true;
    }
    return false;
}

1
2
3
4
5
6
7
8
9
10
11
bool isTxt(string fileName)
{
    const char* origin = fileName.c_str();
    const char* end = &origin[fileName.size() -4];
    const char* wanted = ".txt";
    if(*end == *wanted)
    {
        return true;
    }
    return false;
}


Or do you have a better or more appropriate way to code this function?
Last edited on
How about
filname.size() >= 4 && fileName.substr(fileName.size() - 5) == ".txt"
or something similar for your condition?
Yep, I had a feeling I was over complicating this. Thank you Zhuge!
1
2
3
4
5
bool isTxt(string fileName)
{
    boost::path p(fileName);
    return p.extension() == ".txt";
}
:P
Topic archived. No new replies allowed.