Extract file extension: Difference between revisions
Content deleted Content added
→{{header|Go}}: Adjusted code to the changed task description |
→{{header|C}}: Adjusted code to changed requirements |
||
Line 248: | Line 248: | ||
=={{header|C}}== |
=={{header|C}}== |
||
⚫ | |||
{{update|C|The format of a suffix has been clarified, and the test-cases have been replaced with new ones.}} |
|||
<lang C> |
|||
⚫ | |||
#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'. |
/* Returns a pointer to the extension 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 |
return ext; |
||
} |
} |
||
int main(void) |
int main(void) |
||
{ |
{ |
||
const char * |
const char *testcases[][2] = { |
||
" |
{"http://example.com/download.tar.gz", ".gz"}, |
||
" |
{"CharacterModel.3DS", ".3DS"}, |
||
" |
{".desktop", ".desktop"}, |
||
" |
{"document", ""}, |
||
" |
{"document.txt_backup", ""}, |
||
" |
{"/etc/pam.d/login", ""} |
||
}; |
}; |
||
int exitcode = 0; |
|||
for ( |
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++}}== |