Extract file extension: Difference between revisions
Content added Content deleted
(C solution addition.) |
|||
Line 51: | Line 51: | ||
file.odd_one '' |
file.odd_one '' |
||
</pre> |
</pre> |
||
=={{header|C}}== |
|||
<lang C> |
|||
#include <assert.h> |
|||
#include <ctype.h> |
|||
#include <string.h> |
|||
#include <stdio.h> |
|||
/* Returns a pointer to the extension of 'string'. If no extension is found, |
|||
* then returns a pointer to the null-terminator of 'string'. */ |
|||
char* file_ext(const char *string) |
|||
{ |
|||
assert(string != NULL); |
|||
char *ext = strrchr(string, '.'); |
|||
if (ext == NULL) |
|||
return (char*) string + strlen(string); |
|||
for (char *iter = ext + 1; *iter != '\0'; iter++) { |
|||
if (!isalnum(*iter)) |
|||
return (char*) string + strlen(string); |
|||
} |
|||
return ext + 1; |
|||
} |
|||
int main(void) |
|||
{ |
|||
const char *strings[] = { |
|||
"picture.jpg", |
|||
"http://mywebsite.con/picture/image.png", |
|||
"myuniquefile.longextension", |
|||
"IAmAFileWithoutExtension", |
|||
"/path/to.my/file", |
|||
"file.odd_one" |
|||
}; |
|||
for (int i = 0; i < sizeof(strings) / sizeof(strings[0]); ++i) { |
|||
printf("'%s' - '%s'\n", strings[i], file_ext(strings[i])); |
|||
} |
|||
} |
|||
</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 sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
<lang [[C sharp|C#]]> |
<lang [[C sharp|C#]]> |