Hi all, how would you check to see if there was an extension on a string using strcmp?
thanks for any pointers
thanks for any pointers
dukebound85 said:Hi all, how would you check to see if there was an extension on a string using strcmp?
#include <stdio.h>
main() {
char extension[30] = ".foo";
char string[30] = "something.foo";
int i;
for(i=strlen(string); i >= strlen(string) - strlen(extension); i--) {
if(!strcmp(extension, string+i)) {
printf("match\n");
}
}
}
iMeowbot said:If efficiency is the worry, strlen() inside the for() statement would be best avoided. Stuff the results of the expressions into variables first and then loop on those.
int i;
for(i = strlen(string) - 1; i >= 0; i--) {
if(string[i] == '.') {
printf("string has extension starting at character %d\n", i);
break;
}
}
#include <stdio.h>
#include <string.h>
/* check if s1 ends with s2; return 1 if match else 0 */
int
endswith(char *s1, char *s2)
{
char *s1end, *s2end;
s1end = s1 + strlen(s1) + 1;
s2end = s2 + strlen(s2) + 1;
while (--s2end >= s2 && --s1end >= s1) {
if (*s1end != *s2end)
return 0;
}
if (s2end < s2)
return 1;
return 0;
}
int
main()
{
char* filespec[] = { "New Powerbooks next Tuesdayxt",
"I like snails.txt, I really do",
"realfile.txt",
"autoexec.tx",
"txt",
"this is text.txt",
".txt",
"x",
""
};
int i;
for (i=0; *filespec[i]; i++) {
printf("%s: %s\n", filespec[i],
endswith(filespec[i], ".txt") ? "yes" : "no");
}
return 0;
}
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *xor = @".xor";
NSString *fileName = @"myEncryptedFile.xor";
int fileNameLength = [fileName length];
NSString *extension = [fileName substringFromIndex:fileNameLength-4];
if( [extension isEqualToString:xor] )
NSLog(@"Extension is a .xor extension.");
[pool release];
return 0;
}
/* check if s1 ends with s2; return 1 if match else 0 */
int
endswith(char *s1, char *s2)
{
size_t s1len, s2len;
s1len = strlen(s1);
s2len = strlen(s2);
/* a longer string will never fit inside a shorter one. */
if (s2len > s1len)
return 0;
/* scoot s1 over so the length matches s2 */
s1 += (s1len - s2len);
return !strcmp(s1, s2);
}
mindwalkernine said:In Objective-c, this is just a start;
Code:#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString *xor = @".xor"; NSString *fileName = @"myEncryptedFile.xor"; int fileNameLength = [fileName length]; NSString *extension = [fileName substringFromIndex:fileNameLength-4]; if( [extension isEqualToString:xor] ) NSLog(@"Extension is a .xor extension."); [pool release]; return 0; }