"s88" <da*****@gmail.com> writes:
Howdy everyone:
for example, the psudo code is
string ABC;
string DEF;
string cat = ABC+"__"+DEF;
what is the most popular operations in C to make the above psudo code?
for example, I'll do it like that
char *ABC="THIS IS ABC";
char *DEF="THIS IS DEF";
int size = sizeof ABC + sizeof DEF + sizeof "__";
char *new_str = (char *)malloc(size);
strcpy(new_str,ABC);
strcat(new_str,"__");
strcat(new_str,DEF);
...
Does anyone have better method?
sizeof ABC gives you the size of the pointer, not the length of the
string. You also have to allow for the trailing '\0' that marks the
end of the string. (And all-caps names are conventionally used for
macros, not for variables.)
char *abc = "THIS IS ABC";
char *def = "THIS IS DEF";
size_t size = strlen(abc) + strlen("__") + strlen(def) + 1;
char *new_str = malloc(size); /* Note: No cast */
strcpy(new_str, abc);
strcat(new_str, "__");
strcat(new_str, def);
Or the last three lines could be replaced by:
sprintf(new_str, "%s%s%s", abc, "__", def);
but using sprintf is likely to impose extra overhead.
The strlen("__") is arguably inefficient, since the length is known at
compilation time, but this issue goes away (read on).
The multiple occurrences of "__" are a potential problem, since it's
difficult to keep them all in sync. I'd declare another pointer
variable:
char *underscores = "__";
which can then be treated the same way as abc and def.
Here's a function that encapsulates the whole thing:
/*
* Returns a pointer to a string consisting of s1, s2, and s3
* catenated together. The caller is responsible for free()ing
* the allocated memory.
*/
char *cat3(char *s1, char *s2, char *s3)
{
char *result = malloc(strlen(s1) + strlen(s2) + strlen(s3) + 1);
strcpy(result, s1);
strcat(result, s2);
strcat(result, s3);
return result;
}
...
char *abc = "THIS IS ABC";
char *def = "THIS IS DEF";
char *new_str = cat3(abc, "__", def);
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.