Skip to content

Instantly share code, notes, and snippets.

@EmilHernvall
Created May 3, 2011 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilHernvall/953768 to your computer and use it in GitHub Desktop.
Save EmilHernvall/953768 to your computer and use it in GitHub Desktop.
Experiment with interpolating strings
#include <stdio.h>
#include <stdlib.h>
int expand(char *target, int size, char *format, char **params, int count)
{
int i, placeholders = 0;
for (i = 0; i < strlen(format); i++) {
if (format[i] == '?') {
placeholders++;
}
}
if (placeholders != count) {
return 1;
}
int j = 0, k = 0;
for (i = 0; i < strlen(format); i++) {
if (format[i] == '?') {
int len = strlen(params[k]);
if (j + len > size) {
break;
}
target[j] = 0;
strcat(target, params[k]);
j += strlen(params[k]);
k++;
} else {
target[j] = format[i];
j++;
}
}
target[j] = 0;
return 0;
}
int main(void)
{
char *format = "FOO(?, ?, ?)";
char target[1024];
char *params[3] = { "emil", "hannes", "lydia" };
expand(target, sizeof(target), format, params, 3);
printf("%s\n", target);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment