Hatena::Groupcprogramming

てーげーC言語

2009-02-09

3-3

| 00:59

力技すぎる・・

アンサーブックの解答がすごいうまいと思った。ていうかこういうのどうやって書けるのか?

#include <stdio.h>
#define MAX_LENGTH 1024

void expand(char* s1, char* s2);

enum status{NONE, FROM_ARI, TO_ARI};

int main()
{
  char s2[MAX_LENGTH];

  expand("a-z", s2);
  printf("%s\n", s2);

  expand("a-b-c", s2);
  printf("%s\n", s2);

  expand("a-z0-9", s2);
  printf("%s\n", s2);

  expand("-a-z", s2);
  printf("%s\n", s2);

  expand("a-z-", s2);
  printf("%s\n", s2);

  return 0;
}

void expand(char* s1, char* s2) 
{
  char from, to, last;
  enum status sts;
  
  sts = NONE;
  from = to = '\0';
  
  while(*s1) {
    switch(*s1) {
      case '-':
        if (sts == NONE || sts == TO_ARI) {
          *s2++ = *s1;
          sts = NONE;
        }
        last = *s1;
        break;
      default:
        if (sts == NONE || sts == TO_ARI) {
          from = *s1;
          sts = FROM_ARI;
        } else if (sts == FROM_ARI) {
          to = *s1;
          while (from <= to) {
            *s2++ = from;
            from++;
          }
          sts = FROM_ARI;
          from = to+1;
        }
        last = *s1;
        break;
    }
    s1++;
  }

  if (last == '-')
    *s2++ = last;

  *s2 = '\0';
}
# ./a.out                
abcdefghijklmnopqrstuvwxyz
abc
abcdefghijklmnopqrstuvwxyz123456789
-abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz-

ゲスト



トラックバック - http://cprogramming.g.hatena.ne.jp/tohtas/20090209