Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 30, 2009 06:59
Show Gist options
  • Save shaobin0604/222192 to your computer and use it in GitHub Desktop.
Save shaobin0604/222192 to your computer and use it in GitHub Desktop.
/*
* Exercise 2-4. Write an alternative version of squeeze(s1,s2) that deletes
* each character in s1 that matches any character in the string s2.
*/
#include <stdio.h>
#include <stdlib.h>
void squeeze(char s1[], const char s2[]);
int indexof(const char s[], char c);
/* Return the index of character c in string s, if not found return -1
*
* @param s const char*
* @param c char
*
* @return the index if found, otherwise -1
*
*/
int indexof(const char s[], char c) {
int i = 0;
while ('\0' != s[i]) {
if (c == s[i])
return i;
i++;
}
return -1;
}
/* Deletes each character in s1 that matches any character in the string s2.
*
* @param s1 char*
* @param s2 const char*
*/
void squeeze(char s1[], const char s2[]) {
int i, j;
for (i = j = 0; '\0' != s1[i]; i++) {
if (indexof(s2, s1[i]) == -1)
s1[j++] = s1[i];
}
s1[j] = '\0';
}
int main(void) {
char s1[] = "asdfasdfasdf";
char s2[] = "asdf";
char r[] = "";
squeeze(s1, s2);
if (strcmp(r, s1) == 0)
printf("expected -> %s actual -> %s: equal\n", r, s1);
else
printf("expected -> %s actual -> %s: not equal\n", r, s1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment