Dave \Crash\ Dummy
5/15/2011 11:39:00 AM
"janus" <emekamicro@gmail.com> schrieb im Newsbeitrag
news:4e9b5846-88aa-4cf8-b055-8b65c45b5cfa@glegroupsg2000goo.googlegroups.com...
> Hello All,
>
> From language like Python I could do the following;
>
> foo = ["New York", "New Jersey","New London"]
> foo.join(" ")
> That would join then.
>
> In C, how am I going to reproduce the same?
> Let me try first.
> I feeling is to go this way
>
>
> char newyork[] = "New York";
>
> char newyork[] = "New London";
char newlondon[] ...
> char newyork[] = "New Jersey";
char newjersey[] ...
> int accnum = strlen(newyork) + strlen(newlondon) + strlen(newjersey);
> char mystring[accnum];
That might not compile on every machine, since accnum is not necessary
constant. And you forgot 2 spaces and the terminating '\0' character. You
also forgot to initialize mystring with an empty string. That might lead to
memory corruption. Use this instead.
char mystring[sizeof(newyork) - 1 + sizeof(newlondon) - 1 +
sizeof(newjersey) - 1 + 2 + 1] = "";
> strncat(mystring, newyork , sizeof(mystring)-strlen(newyork)-1);
> strcat(mystring, " ");
> strncat(mystring, newlondon , sizeof(mystring)-strlen(newlondon)-1);
> strcat(mystring, " ");
> strncat(mystring, newjersey , sizeof(mystring)-strlen(newjersey)-1)
if you declare mystring automatically with sufficient size as above with
sizeof(), then you can reduce the overhead of strlen() with strcat in place
of strncat.
But even strcat needs to loop through mystring in order to find it's current
end. You can reduce this overhead with:
strcpy(mystring, newyork);
mystring[sizeof(newyork) - 1] = ' ';
strcpy(mystring, sizeof(newyork) - 1 + 1, newlondon);
mystring[sizeof(newyork) - 1 + 1 + sizeof(newlondon) - 1] = ' ';
strcpy(mystring, sizeof(newyork) - 1 + 1 + sizeof(newlondon) - 1 + 1,
newjersey);