I want to do something like looks like this (obviously not valid c code, though):
char test[] = "you";
char new[] = "hey %s over there", test; // Want to get back "hey you over there"
Here’s my way, but it seems too complicated. Get the len of both the test and new, create a new string buffer that can hold both lengths, concatenate new and test to the string buffer. Is there a better way to do this?
Also char hi[] = "hi" vs char *hi = "hi". What’s the difference?
Well, that’s the time-honored traditional way of doing it in C, though I think you meant the length of
testand the string literal sincenewdoesn’t have a length until you write the data into it.And, as an aside, if you ever expect that your code will be used in a C++ compiler, please don’t call your variables
new🙂 Although I’m assuming that was just a quick and dirty code sample sincenewisn’t a good descriptive name for a variable anyway (newString, or something similar, would be better).If you’re likely to be doing it a lot, there’s no problem with writing a helper function that does all the grunt work for you. That may make your code look cleaner but I’d simply go for your current solution using
strcpy/strcat/strlen/sprintfet al.Or, you can use a third-party piece of code like the better string library, licences and management attitudes permitting (the licences are BSD/GPL but management can still sometimes be a problem).
It has the advantage of not dragging in a lot of extraneous functionality as some third-party libraries are wont to do. All it does is the string handling.
As to the difference between these two:
the first gives you a modifiable character array and the latter does not (try
hi[0] = 'a';in both cases, doing so with the latter would be undefined behaviour). The latter also allows you to change the value of thehipointer to point somewhere else.