473,395 Members | 1,442 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

standard operations about string operation

s88
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?
Thanx!

Nov 14 '05 #1
2 4175
"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.
Nov 14 '05 #2
s88 <da*****@gmail.com> wrote:
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 "__";
First of all, sizeof won't tell you the length of the string
when you use it on a char pointer. It tells you how much memory
youu need for the object it's applied to. Since both 'ABC'and
'DEF' are char pointers you will not get the length of the strings
they point to but how much space each pointer needs. The only
correct use of sizeof here is that for the string literal. Also,
the result of sizeof is size_t why don't you use that? Moreover,
that's the argument type malloc() expects.
char *new_str = (char *)malloc(size);
Since the way you use sizeof to determine the amount of memory
doesn't work you need something like e.g.

char *new_str = malloc( strlen( ABC ) + strlen( DEF )
+ sizeof "__" );

(The 'sizeof "__"' will return 3 since it also counts the
trailing '\0', so you end up with enough space for the
final string, including space for the '\0' at the end).
There's probably no good reason to cast the return value of
malloc() unless you try to compile this with a C++ compiler.
All else you get from this is keeping the compiler from com-
plaining if you forget to include <stdlib.h>. And, finally,
you should of course check the return value of malloc() for
failure before using what 'new_str' points to.
strcpy(new_str,ABC);
strcat(new_str,"__");
strcat(new_str,DEF);
...
Does anyone have better method?


That's one method. Another one would be e.g.

sprintf( new_str, "%s__%s", ABC, DEF );

or variations of that. What's better depends a lot on what you
mean by "better". Execution speed, readability of code or some-
thing else?
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a...
43
by: Steven T. Hatton | last post by:
Now that I have a better grasp of the scope and capabilities of the C++ Standard Library, I understand that products such as Qt actually provide much of the same functionality through their own...
9
by: kernelxu | last post by:
hi,everybody. I calling function setbuf() to change the characteristic of standsrd input buffer. some fragment of the progrem is: (DEV-C++2.9.9.2) #include <stdio.h> #include <stdlib.h> int...
17
by: Chad Myers | last post by:
I've been perf testing an application of mine and I've noticed that there are a lot (and I mean A LOT -- megabytes and megabytes of 'em) System.String instances being created. I've done some...
0
by: jimmyfishbean | last post by:
Hi, Please could comeone tell me how to programatically read the input message parts for a web service operation. I have a web service that has many operations. One of these operations (say...
36
by: mrby | last post by:
Hi, Does anyone know of any link which describes the (relative) performance of all kinds of C operations? e.g: how fast is "add" comparing with "multiplication" on a typical machine. Thanks!...
3
by: Hallvard B Furuseth | last post by:
I'm wondering how to design this: An API to let a request/response LDAP server be configured so a user-defined Python module can handle and/or modify some or all incoming operations, and later...
132
by: Frederick Gotham | last post by:
If we look at a programming language such as C++: When an updated Standard comes out, everyone adopts it and abandons the previous one. It seems though that things aren't so clear-cut in the C...
9
by: j_depp_99 | last post by:
My program reads in hex values from a file and then performs arithmetic operations on them. All works well except when I use large hex values and my answers are incorrect. For example...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.