今天在開發(fā)時(shí)遇到一個(gè)問題,就是dos內(nèi)容直接輸出到網(wǎng)頁上的時(shí)候,并沒有換行,也不分段,所有字符密密麻麻連在一起了。比如在dos里執(zhí)行ping howtostagehomes.com的命令,得到的是很整體的可讀性很高的輸出結(jié)果。
但是,如果把這些內(nèi)容直接復(fù)制到網(wǎng)頁上,并不會(huì)有這樣的格式化結(jié)果,而是出現(xiàn)如下面的一堆字符,完全不具可讀性。
Pinging www.a.shifen.com [220.181.112.143] with 32 bytes of data: Reply from 220.181.112.143: bytes=32 time=43ms TTL=54 Reply from 220.181.112.143: bytes=32 time=44ms TTL=54 Reply from 220.181.112.143: bytes=32 time=43ms TTL=54 Reply from 220.181.112.143: bytes=32 time=43ms TTL=54 Ping statistics for 220.181.112.143: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 43ms, Maximum = 44ms, Average = 43ms
這就需要程序來進(jìn)行字符轉(zhuǎn)換。dos輸出的結(jié)果,主要包含4個(gè)不可見字符,分別是回車符、換行符、制表符和空格符。
我們不能輕而易舉的直接進(jìn)行字符替換就能完事,因?yàn)槟切┳址遣豢梢姷?,必須通過間接的方式查找出這些字符,然后才可替換掉。
處理這個(gè)問題,我用上了ASCII碼,通過ASCII碼表,可查出這4個(gè)不可見字符的ASCII值分別是回車符(13)、換行符(10)、制表符(9)和空格符(20),現(xiàn)在只需要把dos輸出的結(jié)果每個(gè)字符進(jìn)行ASCII轉(zhuǎn)換,找出這4個(gè)不可見字符,替換成相應(yīng)的符號(hào)即可。其中回車符和換行符均替換為“<br>”,空格符則替換為“ ”,而制表符替換為三個(gè)空格符的HTML代碼“ ”,這樣便能格式化這堆密密麻麻的字符串了。
看看網(wǎng)頁輸出的格式化結(jié)果:
Pinging www.a.shifen.com [220.181.112.143] with 32 bytes of data:
Reply from 220.181.112.143: bytes=32 time=43ms TTL=54
Reply from 220.181.112.143: bytes=32 time=44ms TTL=54
Reply from 220.181.112.143: bytes=32 time=43ms TTL=54
Reply from 220.181.112.143: bytes=32 time=43ms TTL=54
Ping statistics for 220.181.112.143:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 43ms, Maximum = 44ms, Average = 43ms
核心程序代碼(asp.net):
1、字符轉(zhuǎn)ASCII值函數(shù)
public static int Asc(string character)
{
if (character.Length == 1)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
return (intAsciiCode);
}
else
{
throw new Exception("Character is not valid.");
}
}
2、字符替換
假設(shè)dos輸出的結(jié)果賦給變量strResult,格式化后的結(jié)果賦給變量strResultFormat。
for (int i = 0; i < strResult.Length; i++)
{
if (Convert.ToInt32(Asc(strResult.Substring(i, 1))) == 13) //回車
{
strResultFormat = strResultFormat + "<br>";
}
else if (Convert.ToInt32(Asc(strResult.Substring(i, 1))) == 10) //換行
{
strResultFormat = strResultFormat + "<br>";
}
else if (Convert.ToInt32(Asc(strResult.Substring(i, 1))) == 32) //空格
{
strResultFormat = strResultFormat + " ";
}
else if (Convert.ToInt32(Asc(strResult.Substring(i, 1))) == 9) //制表符(默認(rèn)是3個(gè)空格的長度)
{
strResultFormat = strResultFormat + " ";
}
else
{
strResultFormat = strResultFormat + strResult.Substring(i, 1);
}
}
最后,附上完整ASCII碼對(duì)照表。完整ASCII碼對(duì)照表.txt