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);
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.
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.
From a readability standpoint, f-string literals are more aesthetically pleasing and easier to read than string concatenation.
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.
sprintf(prefix,"%s: %s: %s",argv[0],cmd_argv[0],cmd_argv[1]);
Or snprintf
to prevent buffer overruns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With