-
-
Save water-air-flash/23e70a8a87ce6b550158cec58ba61082 to your computer and use it in GitHub Desktop.
[2010-01] I guess I was trying string contactenation in C
This file contains hidden or 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
| //&>/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