Skip to main content
GameDev.net gamedev.net
🔒 Locked

String manipulation

Started by mrmrcoleman Jun 23, 2004 at 8:32 AM 2 replies 650+ views
Original Post
mrmrcoleman
mrmrcoleman
Hello, I have a string, well a char*, which contains the location of a local animation file e.g. "c:\animations\anim1.avi" What is the best way to change the extension so that I end up with a char* containing "c:\animations\anim1.bmp" ?? Thanks in advance. Mark Coleman
Empirical
Empirical
int Sz=strlen(MyString);
*(int *)(MyString+Sz-4)='pmb.';


:P
Agony
Agony
[Edit]
If you're wanting to just use C, then you could use strrchr() to find the last '.' in the string, and strcpy() to copy the new extension over the old one.

//Disclaimer NOT [thoroughly] TESTED!!!char FileName[256];strcpy(FileName, "c:\\animations\\anim1.avi");strcpy(strrchr(FileName, '.'), ".bmp");

It's not inherently memory-safe, though, as is the case with many C string manipulations.
[/Edit]

If you're using C++, though, and don't mind using std::string, then you can do it pretty easily. If you know that the two extensions are the same length, as in the example, then this simplifies things even more.

//Disclaimer:  [also] NOT [thoroughly] TESTED!!!std::string FileName;//If you're not guaranteed to have equal size extensions:FileName = "c:\\animations\\anim1.avi";FileName = FileName.substr(0, FileName.rfind('.')) + ".bmp";//If you are guaranteed to have equal size extensions:FileName = "c:\\animations\\anim1.avi";FileName.replace(FileName.rfind('.'), 4, ".bmp");
The second one should be more efficient, but the first is more reliable, since it works on any extension.

@Empirical: That's insane[ly clever]. [wow][smile]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
mrmrcoleman
mrmrcoleman
Sorry for the late reply, but thanks guys. The code works perfectly.

Mark Coleman

Topic Locked

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

Sign in to reply to this topic.