Skip to content

Instantly share code, notes, and snippets.

@jeremyBanks
Created September 12, 2008 09:17
Show Gist options
  • Save jeremyBanks/10415 to your computer and use it in GitHub Desktop.
Save jeremyBanks/10415 to your computer and use it in GitHub Desktop.
[2010-01] I guess I was trying string contactenation in C
//&>/dev/null;x="${0%.*}";[ ! "$x" -ot "$0" ]||(rm -f "$x";cc -o "$x" "$0")&&"$x" $*;exit
#import <stdio.h>
#import <stdlib.h>
char* joinStrings(char** strings, int numStrings, char* seperator) {
// Handle empty case which would cause problems.
if (numStrings == 0)
return "";
// Determine the length of the seperator string.
int seperatorLength = 0;
while (seperator[seperatorLength])
++seperatorLength;
// Start with 1 char for the null terminator...
int finalSize = 1;
// ...add the length of the first string...
int characterIndex;
for (characterIndex = 0; strings[0][characterIndex]; ++characterIndex)
++finalSize;
int stringIndex;
// ...add the lengths of subsequent strings and the seperator.
for (stringIndex = 1; stringIndex < numStrings; ++stringIndex) {
finalSize += seperatorLength;
for (characterIndex = 0; strings[stringIndex][characterIndex]; ++characterIndex)
++finalSize;
}
// Allocate memory our new string...
char* newString = (char*) malloc(sizeof(char) * finalSize);
int finalIndex = 0;
// ...copy the first string in....
for (characterIndex = 0; strings[0][characterIndex]; ++characterIndex)
newString[finalIndex++] = strings[0][characterIndex];
// ...copy the subsequent strings and seperators.
for (stringIndex = 1; stringIndex < numStrings; ++stringIndex) {
for (characterIndex = 0; seperator[characterIndex]; ++characterIndex)
newString[finalIndex++] = seperator[characterIndex];
for (characterIndex = 0; strings[stringIndex][characterIndex]; ++characterIndex)
newString[finalIndex++] = strings[stringIndex][characterIndex];
}
// Terminate our new string...
newString[finalIndex] = (char) 0;
// ...and return it.
return newString;
}
#define numStrings 30
int main(int argc, char* argv[]) {
char* strings[numStrings] = {
"Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta", "Eta",
"Theta", "Iota", "Kappa", "Lambda", "Mu", "Nu", "Xi", "Omicron",
"Pi", "Rho", "Sigma", "Tau", "Upsilon", "Phi", "Chi", "Omega",
"Digamma", "Stigma", "Heta", "San", "Sho", "Qoppa", "Sampi"
};
char* seperator = ", ";
int n;
for (n = 1; n <= numStrings; ++n)
printf("%s\n", joinStrings(strings, n, seperator));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment