Extract file extension: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: Adjusted code to the changed task description)
(→‎{{header|C}}: Adjusted code to changed requirements)
Line 248: Line 248:
=={{header|C}}==
=={{header|C}}==


<lang C>#include <assert.h>
{{update|C|The format of a suffix has been clarified, and the test-cases have been replaced with new ones.}}

<lang C>
#include <assert.h>
#include <ctype.h>
#include <ctype.h>
#include <string.h>
#include <string.h>
#include <stdio.h>
#include <stdio.h>


/* Returns a pointer to the extension of 'string'. If no extension is found,
/* Returns a pointer to the extension of 'string'.
* then returns a pointer to the null-terminator of 'string'. */
* If no extension is found, returns a pointer to the end of 'string'. */
char* file_ext(const char *string)
char* file_ext(const char *string)
{
{
Line 267: Line 264:


for (char *iter = ext + 1; *iter != '\0'; iter++) {
for (char *iter = ext + 1; *iter != '\0'; iter++) {
if (!isalnum(*iter))
if (!isalnum((unsigned char)*iter))
return (char*) string + strlen(string);
return (char*) string + strlen(string);
}
}


return ext + 1;
return ext;
}
}


int main(void)
int main(void)
{
{
const char *strings[] = {
const char *testcases[][2] = {
"picture.jpg",
{"http://example.com/download.tar.gz", ".gz"},
"http://mywebsite.con/picture/image.png",
{"CharacterModel.3DS", ".3DS"},
"myuniquefile.longextension",
{".desktop", ".desktop"},
"IAmAFileWithoutExtension",
{"document", ""},
"/path/to.my/file",
{"document.txt_backup", ""},
"file.odd_one"
{"/etc/pam.d/login", ""}
};
};


int exitcode = 0;
for (int i = 0; i < sizeof(strings) / sizeof(strings[0]); ++i) {
for (size_t i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) {
printf("'%s' - '%s'\n", strings[i], file_ext(strings[i]));
const char *ext = file_ext(testcases[i][0]);
if (strcmp(ext, testcases[i][1]) != 0) {
fprintf(stderr, "expected '%s' for '%s', got '%s'\n",
testcases[i][1], testcases[i][0], ext);
exitcode = 1;
}
}
}
return exitcode;
}
</lang>
}</lang>
{{out}}
<pre>
'picture.jpg' - 'jpg'
'http://mywebsite.con/picture/image.png' - 'png'
'myuniquefile.longextension' - 'longextension'
'IAmAFileWithoutExtension' - ''
'/path/to.my/file' - ''
'file.odd_one' - ''
</pre>


=={{header|C++}}==
=={{header|C++}}==