Problem overview
The function fileExtension receives a file name and returns its extension: the part after the last dot. The name "photo.jpeg" has one dot, so the extension is "jpeg". A name can have several dots. In "archive.tar.gz" only what follows the last dot counts, so the answer is "gz". The extension keeps its letters as they are: "README.MD" gives "MD".
The name always contains at least one dot, and it neither starts nor ends with one. It has no spaces, only English letters, digits, dots, hyphens and underscores.
Approach
Many languages would split the name at every dot and take the last part. C++ strings have no split method, but splitting isn't needed. What matters is where the last dot is. Everything after that position is the extension.
The std::string class offers two searches that fit. find looks from the start and reports the first match, and rfind looks from the end and reports the last one. For this task the last dot is wanted, so the right choice is rfind.
Step by step
- Find the last dot.
fileName.rfind(".")returns the index of the last dot, and the lesson stores it in anintnameddot. For"photo.jpeg"it is 5, and for"archive.tar.gz"it is 11. - Take the text after it.
fileName.substr(dot + 1)starts one character past the dot, which skips the dot itself. With no second argument,substrgoes to the end of the string, which is where the extension ends.
The solution in C++
class Solution {
public:
string fileExtension(string fileName) {
int dot = fileName.rfind(".");
return fileName.substr(dot + 1);
}
};
What to know about the C++ involved:
findversusrfind. On"archive.tar.gz",find(".")gives index 7, the first dot, and the code would return"tar.gz". Onlyrfindreaches the last dot.- The return type of
rfind. It returns an unsignedsize_t. When the character is missing, it returns the special valuestring::npos, which is the largest unsigned number. Stored in anint, that value becomes -1, sodot + 1is 0 andsubstr(0)returns the whole name. For a name with no dot,"README", the function returns"README". The lesson's names always have a dot, so this case doesn't arise. - A string argument.
rfindaccepts a string literal such as"."or a single character such as'.'. - A new string.
substrcopies the piece it selects and doesn't changefileName.
Edge cases and common mistakes
- Using
find. It stops at the first dot, which is wrong for names with several dots. - Forgetting the
+ 1.substr(dot)includes the dot, so the result would be".jpeg". - Changing the case. The extension is returned exactly as written, so
"MD"stays upper case. - Several dots. A name such as
"archive.tar.gz"has the extension"gz", and the same two lines handle it. - A name without a dot. The result would be the whole name, as explained above. A robust program would check for
string::nposfirst and return an empty string. The lesson's constraints guarantee a dot, so the lesson doesn't need that check.
Testing
"photo.jpeg"gives"jpeg"."archive.tar.gz"gives"gz"."README.MD"gives"MD".
