Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to concatenate multiple strings in c?

Tags:

c

Is there a better way to concatenate multiple strings together in c other than having multiple calls to strcat() all in a row, like below?

char prefix[100] = ""; strcat(prefix, argv[0]); strcat(prefix, ": "); strcat(prefix, cmd_argv[0]); strcat(prefix, ": "); strcat(prefix, cmd_argv[1]); perror(prefix); 
like image 241
user738804 Avatar asked May 04 '11 21:05

user738804


People also ask

What is the most efficient way to concatenate many strings together?

If you are concatenating a list of strings, then the preferred way is to use join() as it accepts a list of strings and concatenates them and is most readable in this case. If you are looking for performance, append/join is marginally faster there if you are using extremely long strings.

How can you concatenate multiple strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Are F strings better than concatenation?

From a readability standpoint, f-string literals are more aesthetically pleasing and easier to read than string concatenation.

Is concatenation faster than join?

Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.


1 Answers

sprintf(prefix,"%s: %s: %s",argv[0],cmd_argv[0],cmd_argv[1]); 

Or snprintf to prevent buffer overruns.

like image 163
Jacob Avatar answered Sep 29 '22 16:09

Jacob