Skip to content

Instantly share code, notes, and snippets.

@murphybytes
Last active December 15, 2015 01:59
Show Gist options
  • Select an option

  • Save murphybytes/5183957 to your computer and use it in GitHub Desktop.

Select an option

Save murphybytes/5183957 to your computer and use it in GitHub Desktop.
My implementation of an O(n) algorithm that removes characters from a string.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main( int argc, char* argv[] ) {
if( argc < 3 ) {
printf( "Usage: repl <word> <char to replace>\n" );
return 1;
}
char* s = (char*)malloc( strlen( argv[1] ) + 1 ) ;
strcpy( s, argv[1] );
const char r = argv[2][0];
int i = 0;
int j = 0;
int k = strlen( s );
while( 1 ) {
if( s[i] == r ) {
j = j <= i ? i + 1 : j;
while( j < k ) {
if( s[j] != r ) {
s[i] = s[j];
s[j] = r;
break;
}
j++;
}
}
if( j >= k ) break;
i++;
}
s[i] = 0;
printf( "%s\n", s );
free( s );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment