/** * Create a string, clone it and compare them */ void test1() { // for the sake of clarity, we don't check for errors in this demonstration // this function call allocates a number and sets it to 0 MyString * s1 = myStringAlloc(); MyStringRetVal rVal = myStringSetFromCString(s1, "Hello world?!?"); MyString * s2 = myStringClone(s1); int res = myStringCompare(s1, s2); if (res != 0) { exitBad(1); } myStringFree(s1); myStringFree(s2); }
/** * @brief Asks for 2 strings, compare between them and write to file the results. */ int main() { char str1[MAX_LENGTH] = {0}, str2[MAX_LENGTH] = {0}; printf("Enter the first string:\n"); fgets(str1, MAX_LENGTH, stdin); printf("Enter the second string:\n"); fgets(str2, MAX_LENGTH, stdin); // Replace the last char '\n' that fgets automatic puts in the end of the strings with '\0' int lenStr1 = strlen(str1); int lenStr2 = strlen(str2); str1[lenStr1 - 1] = '\0'; str2[lenStr2 - 1] = '\0'; MyString* myStr1 = myStringAlloc(); MyString* myStr2 = myStringAlloc(); myStringSetFromCString(myStr1, str1); myStringSetFromCString(myStr2, str2); printf("Compare between the 2 strings and writing the result to test.out...\n"); int compare = myStringCompare(myStr1, myStr2); if (compare <= 0) { writeResult(myStr1, myStr2); } else { writeResult(myStr2, myStr1); } printf("Done.\n"); myStringFree(myStr1); myStringFree(myStr2); return 0; }
/** * get two strings from ints, concatenate them and parse them back to an int */ void test2() { int first = 10, second = 5; // This time, we check for errors. MyString * high = NULL; MyString * low = NULL; high = myStringAlloc(); low = myStringAlloc(); myStringSetFromInt(high, first); myStringSetFromInt(low, second); myStringCat(high, low); if (myStringToInt(high) != 105) { exitBad(1); } // clean up. myStringFree(high); myStringFree(low); }
/** * @brief Sets the value of str to the value of other. * @param str the MyString to set * @param other the MyString to set from * RETURN VALUE: * @return MYSTRING_SUCCESS on success, MYSTRING_ERROR on failure. */ MyStringRetVal myStringSetFromMyString(MyString *str, const MyString *other) { if (other == NULL || str == NULL) { return MYSTRING_ERROR; } myStringFree(str); str = myStringClone(other); if (str == NULL) { return MYSTRING_ERROR; } return MYSTRING_SUCCESS; }