Skip to content

Instantly share code, notes, and snippets.

@kezhuw
Created March 29, 2012 03:31
Show Gist options
  • Save kezhuw/2232989 to your computer and use it in GitHub Desktop.
Save kezhuw/2232989 to your computer and use it in GitHub Desktop.
#include "remove_multiple_spaces.h"
#include <assert.h>
size_t
remove_multiple_spaces(char *str) {
assert(str != 0);
if (str[0] == '\0') {
return 0;
}
char *next, *iter;
int prevc, iterc;
prevc = *str;
next = str+1;
iter = str+1;
for (iterc = *iter; (iterc = *iter) != '\0'; iter++) {
if (iterc == ' ' && prevc == iterc) {
continue;
}
*next++ = iterc;
prevc = iterc;
}
*next = '\0';
return next-str;
}
#ifndef __REMOVE_MULTIPLE_SPACES_H
#define __REMOVE_MULTIPLE_SPACES_H
#include <stddef.h>
// Combine continuous spaces into one, return result string length.
// assert(str != NULL);
//
// e.g.:
//
// "" ==> ""
// " " ==> " "
// " ab c d e " ==> " ab c d e "
size_t remove_multiple_spaces(char *str);
#endif
#include "remove_multiple_spaces.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *
dupstr(const char *str) {
size_t len = strlen(str);
char *ret = malloc(len+1);
strcpy(ret, str);
return ret;
}
static void
delstr(char *dup) {
free(dup);
}
struct pair {
char *origin;
char *expect;
};
static const struct pair pairs[] = {
{"", ""},
{" ", " "},
{" ", " "},
{" a", " a"},
{"a ", "a "},
{" a ", " a "},
{" abcdef ", " abcdef "},
{" abcdef fe ", " abcdef fe "},
{" abc def ghi opq", " abc def ghi opq"},
{" \n \nabc cde ", " \n \nabc cde "},
{NULL, NULL},
};
static void
ForeachPairs(const struct pair *tests, void (*each)(const struct pair *)) {
const struct pair *iter;
for (iter = tests; iter->origin != NULL; iter++) {
each(iter);
}
}
// TODO Escape special characters, e.g., \n, \t.
static void
CheckReturn(const struct pair *pi) {
char *str = dupstr(pi->origin);
size_t len = remove_multiple_spaces(str);
if (len != strlen(str)) {
fprintf(stderr,
"remove_multiple_spaces(%s) got {{%s}}, length %zu, return %zu.\n",
pi->origin, str, strlen(str), len);
abort();
}
delstr(str);
}
static void
CheckExpect(const struct pair *pi) {
char *str = dupstr(pi->origin);
remove_multiple_spaces(str);
if (strcmp(str, pi->expect) != 0) {
fprintf(stderr,
"remove_multiple_spaces(%s) got {{%s}}, expect {{%s}}.\n",
pi->origin, str, pi->expect);
abort();
}
delstr(str);
}
static void
TestReturn(const struct pair *tests) {
ForeachPairs(tests, CheckReturn);
}
static void
TestExpect(const struct pair *tests) {
ForeachPairs(tests, CheckExpect);
}
int
main(void) {
setvbuf(stderr, 0, _IONBF, 0);
setvbuf(stdout, 0, _IONBF, 0);
TestReturn(pairs);
TestExpect(pairs);
fprintf(stdout, "remove_multiple_spaces PASSED\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment