Compare, squeeze and reverse C strings
Comparing two strings:
int compare(const char *str1, const char *str2) { // base case if (*str1 == '\0' && *str2 == '\0') return 1; // heads match, check tails else if (*str1 == *str2) return compare(++str1, ++str2); return 0; }
Squeezing a character:
void squeeze(const char *in, char *out) { while (*in == ' ') in++; if (*in == '\0') { *(++out) = '\0'; return; } else { *out = *in; return squeeze(++in, ++out); } }
Reversing a string (inplace, smart way)
void inplace(char *str) { char tmp; char *end = str; while (*end) { end++; } end--; while (str < end) { tmp = *str; *str++ = *end; *end-- = tmp; } }
Reversing a string (the stupid way with recursion)
// start = 0, end = strlen(in)-1 void reverse(const char in[], char out[], unsigned int start, int end) { if (start == strlen(in)) return; out[start] = in[end]; reverse(in, out, ++start, --end ); }