Skip to main content
GameDev.net gamedev.net
๐Ÿ”’ Locked

Help with strings

Started by Jazonxyz Sep 19, 2008 at 8:45 AM 1 replies 900+ views
Original Post
Jazonxyz
Jazonxyz
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.
Kippesoep
Kippesoep
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!
Kippesoep
DevFred
DevFred
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;}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.