Jump to content
  • Advertisement
Sign in to follow this  
Jazonxyz

Help with strings

This topic is 3619 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!