Created
May 3, 2011 17:26
-
-
Save EmilHernvall/953768 to your computer and use it in GitHub Desktop.
Experiment with interpolating strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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