Sign in to follow this  
Jazonxyz

Help with strings

Recommended Posts

I have a variable like this: char FileName[100] = "Filaname.bmp"; how can I replace the last four characters so that it reads: "Filename.lua"? Thanks in advance.

Share this post


Link to post
Share on other sites

int length = strlen (FileName);
if (length >= 4)
{
char *insertion = FileName + length - 4;
strcpy (insertion, ".lua");
}




that said, an extension need not be 3 letters. (You can use strrchr to find the last "." in a string -- check it for NULL if there is no dot). On the whole, you should be very careful when using C style strings. If at all possible, use C++ style strings. And never trust any user input!

Share this post


Link to post
Share on other sites
I assume you are using C, not C++, because in C++, you'd be using std::string instead of an array of characters.

#include <stdio.h>
#include <string.h>

int bmp2lua(char *filename)
{
char *extension = filename + strlen(filename) - 4;
if (extension < filename || strcmp(extension, ".bmp")) return -1;
strcpy(extension, ".lua");
return 0;
}

int main(void)
{
char FileName[100] = "Filename.bmp";
bmp2lua(FileName);
printf("%s\n", FileName);
return 0;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this