コード圧縮
Posted feedbacks - C#
C#でまじめにやってみた。
(あれ?α置換でも同じようなコード書いた気が)
動けばよかろう、な品質です。
(あれ?α置換でも同じようなコード書いた気が)
動けばよかろう、な品質です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | using System;
using System.Text;
using System.IO;
namespace DouKaku
{
class Program
{
/**
* 内部状態
* 通常,文字リテラル,文字列リテラル,逐語文字列リテラル,行コメント,範囲コメント
*/
enum State { None, Char, RegularStr, VerbatimStr, LineComment, DelimitedComment }
/* コード圧縮を行う */
static string Compress(string code)
{
string WhiteSpace = " \t\r\n"; //空白
string LineTerminator = "\r\n"; //行終端
string Kigou = @"{}[]().,:;+-*/%&|^!~=<>?""'@"; //演算子・記号
StringBuilder sb = new StringBuilder();
State state = State.None;
for (int i = 0 ; i < code.Length ; i++) {
switch (state) {
case State.LineComment: //行コメント
if (LineTerminator.IndexOf(code[i]) >= 0)
state = State.None;
break;
case State.DelimitedComment: //範囲コメント
if (code[i] == '*' && code[i + 1] == '/') {
state = State.None;
i++;
}
break;
case State.RegularStr: //文字列リテラル
case State.Char: //文字リテラル
if (code[i] == '\\')
sb.Append(code[i++]);
else if (code[i] == (state == State.Char ? '\'' : '"'))
state = State.None;
sb.Append(code[i]);
break;
case State.VerbatimStr: //逐語文字列リテラル
if (code[i] == '"')
if (code[i + 1] != '"')
state = State.None;
else {
sb.Append('"');
i++;
}
sb.Append(code[i]);
break;
case State.None: //通常
if (code[i] == '/' && code[i + 1] == '/') {
state = State.LineComment;
} else if (code[i] == '/' && code[i + 1] == '*') {
state = State.DelimitedComment;
i++;
} else if (code[i] == '"') {
state = State.RegularStr;
sb.Append(code[i]);
} else if (code[i] == '\'') {
state = State.Char;
sb.Append(code[i]);
} else if (code[i] == '@' && code[i + 1] == '"') {
state = State.VerbatimStr;
sb.Append("@\"");
i++;
} else if (WhiteSpace.IndexOf(code[i]) >= 0) {
if (WhiteSpace.IndexOf(code[i + 1]) < 0
&& Kigou.IndexOf(code[i + 1]) < 0
&& 0 < sb.Length
&& WhiteSpace.IndexOf(sb[sb.Length - 1]) < 0
&& Kigou.IndexOf(sb[sb.Length - 1]) < 0)
sb.Append(' ');
} else
sb.Append(code[i]);
break;
}
}
return sb.ToString();
}
static void Main(string[] args)
{
try {
string input = File.ReadAllText(args[0]);
string output = Compress(input);
Console.WriteLine(output);
} catch (ApplicationException ex) {
Console.WriteLine(ex.StackTrace);
}
}
}
}
|

sweetie089 #6664() Rating-6/10=-0.60
[ reply ]