Skip to content

Instantly share code, notes, and snippets.

@smertelny
Last active July 9, 2019 19:59
Show Gist options
  • Select an option

  • Save smertelny/152323aba845580421703911f5fbb0d7 to your computer and use it in GitHub Desktop.

Select an option

Save smertelny/152323aba845580421703911f5fbb0d7 to your computer and use it in GitHub Desktop.
Exercise 3-3 from K&R The C programming language Book
/** Exercise 3-3 from K&R The C programming language Book */
#include <stdio.h>
#include <ctype.h>
#define MAX_LENGTH 1000
void expand(char s1[], char s2[]);
int main()
{
char to[MAX_LENGTH];
for (int i = 0; i < MAX_LENGTH; i++)
{
to[i] = 0;
}
char from[] = "---a-b-z-A-Z0-9-----";
expand(from, to);
printf("%s\n", to);
}
void expand(char s1[], char s2[])
{
char previous_char = '\0';
int j = 0;
for (int i = 0; s1[i] != '\0'; i++)
{
char next_char = s1[i + 1];
if (s1[i] == '-' && previous_char != '\0' && next_char != '\0' && previous_char < next_char && isalnum(previous_char) && isalnum(next_char))
{
while(previous_char < next_char - 1)
{
s2[j++] = ++previous_char;
}
previous_char = '\0';
} else {
s2[j++] = s1[i];
previous_char = s1[i];
}
}
s2[j] = '\0';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment