Re: C Style Strings
"kwikius" <andy@servocomm.freeserve.co.uk> wrote
scroopy wrote:
Hi,
I've always used std::string but I'm having to use a 3rd party library
that returns const char*s. Given:
char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";
How do I append the contents of pString2 to pString? (giving "Blah
Blah Blah")
#include <malloc.h>
#include <cstring>
char* concat(const char * str1, const char* str2)
{
char * result = (char*) malloc(strlen( str1) + strlen (str2) + 1);
if( result != NULL){
strcpy(result,str1);
strcat(result, str2);
}
return result;
}
Perfectly unexceptional code.
It won't execute as efficiently as it might, but then most programs can
manipulate a string much faster than a human can read it, however
inefficiently written.
If we want we can do a speed-up
void fastconcat(char *out, char *str1, char *str2)
{
while(*str1)
*out++ = *str1++;
while(*str2)
*out++ = *str2++;
*out = 0;
}
this is a bit of nuisance since it throws the burden of memory allocation
onto the user, it is also rather dangerous sinvce we don't check the buffer.
But it will be very fast. That's the beauty of C, you can roll the function
to the problem you face.
#include <iostream>
#include <string>
char* pString1 = "Blah ";
const char* pString2 = "Blah Blah";
int main()
{
// C-style
char* str = concat(pString1,pString2);
if(str != NULL){
std::cout << str <<'\n';
free(str);
}
// C++ style
std::string str1=std::string(pString1) + pString2;
Ok what's going on here?
You have a string, and now you are calling what looks like a string
constructor to create another type of string. Why do you need two types of
string in the program? Do they behave differently when passed to cout? How
do I know that they will behave in the same way?
std::cout << str1 <<'\n';
}
I'm not sure if that is the optimal C method. Its interesting to note
how much better the C++ version is though!
So what's the big - O analysis of that '+' operation? Where is this
documented? What if I want to sacrifice a bit of safety for speed, as we did
with C? Can I overload the string '+' operator to achieve this?
Apologies to our friends on C++, but this was a provocative post.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm