问题: 分析一个CPP文件中空格行数,纯代码行数,纯注释行数,代码和注释混合行数,总代码行数。
一开始写时,我用了相当混乱的状态标识方法,导致条理不清,很多情况没有考虑到。后来Jumping老人家略花几个小时(小于3小时),华丽丽地敲出了一份标准状态机代码。参考了下,顺便也学了下状态机的基本用法。今天敲完后,总结了几点,状态机的框架和状态模式差不多,为了避免多个switch-case的用法,而采用多态根据输入的条件轮转各种状态。所以状态机的重点还在于分析状态上,因问题不同而不同,也就没有统一的模板。
以下代码以这么个思路进行的。
1,空格行 isCode = false, isComment = false;
2,混合行 isCode = true, isComment = true;
3,代码行 非"//", "/*", " ", "/r"
4,注释行 除了"/""打头
private var codeCount: int = 0;
private var commentCount: int = 0;
private var mixCount: int = 0;
private var totalCount: int = 0;
private var blankCount: int = 0;
public function StateMachine()
{
readFile();
}
public function readFile(): void
{
var load: URLLoader = new URLLoader();
load.addEventListener(Event.COMPLETE, dealControl);
load.load(new URLRequest("D://2.cpp"));
}
public function dealControl(event: Event): void
{
fileStr = String(event.target.data);
fileStr += "/r";
var index: int = 0;
while (fileStr.length != index)
{
currDeal = currDeal(fileStr.charAt(index));
index++;
}
trace("code " + codeCount.toString());
trace("comment " + commentCount.toString());
trace("blankCount " + blankCount.toString());
trace("mixCount " + mixCount.toString());
trace("totalCount " + totalCount.toString());
}
public function normal_Deal(m: String): Function
{
if (lastStr == "")
{
lastStr = m;
return normal_Deal;
}
else if (m == "/r")
{
return normal_EndLine();
}
else if (lastStr == "/" && m == "/" && !isString)
{
isCommentLine = true;
return comment_Deal;
}
else if (lastStr == "/" && m == "*" && !isString)
{
return comment_Deal;
}
else if (m == "/"" || m == "/'")
{
isCode = true;
isString = true;
}
else if (m != " " && m != "/t" && m != "/")
{
isCode = true;
}
lastStr = m;
return normal_Deal;
}
public function comment_Deal(m: String): Function
{
isComment = true;
if(lastStr == "*" && m == "/")
{
return normal_Deal;
}
else if (m == "/r")
{
return comment_EndLine();
}
lastStr = m;
return comment_Deal;
}
public function comment_EndLine(): Function
{
totalCount++;
if (isComment && isCode)
{
mixCount++;
}
else if (isComment && !isCode)
{
commentCount++;
}
lastStr = "";
isCode = false;
isString = false;
if (isCommentLine)
{
isCommentLine = false;
isComment = false;
return normal_Deal;
}
return comment_Deal;
}
public function normal_EndLine(): Function
{
totalCount++;
if (isComment && !isCode)
{
commentCount++;
}
else if (isComment && isCode)
{
mixCount++;
}
else if (!isComment && isCode)
{
codeCount++;
}
else if (!isComment && !isCode)
{
blankCount++;
}
isCode = false
isComment = false;
isString = false;
lastStr = "";
return normal_Deal;
}
}
最后:
本来这个问题早在几个月前就要处理了,到了最近分析html的内容的时候,发现,flex在这方面并不强大,久没碰c之类的底层工具,生疏得无法即时解决问题本身,phython,很好的工具,工具到用时方知不会。这时候,发现自己会的东西,并不是最好的能解决问题的。用flex解决这些问题,犹如隔鞋抓痒,不痛快,不彻底。所以空闲时,还是多练练一些底层工具,没有太多的封装,外加很好的思路,轻装上阵,所向无敌,挺好,挺好。