※ 引述《a030164851 (小加號)》之銘言:
: 因為老師說要讓字串裡面的字元依ASCII Code排序,
: 想讓字元直接比大小系統不讓實作(只有相等可以比),
: 但是找不到方法可以讓字元轉換成ASCII Code!
: 不知道能不能告訴我要怎麼轉換?
: 找過網路跟資料庫,可是多數都是C++的轉換!
:
: --
: ※ 發信站: 批踢踢實業坊(ptt.cc)
: ◆ From: 125.224.118.146
: → carl71321:字元轉int即可 11/06 12:25
: → a030164851:使用轉int也不能比較其大小,大概是因為我用矩陣去存那 11/06 14:48
轉成 int 就是轉成字元的內碼,而且都轉成 int 了還不能比大小?
不過直接轉 int 確實不是 ASCII code (是 Unicode),但至少英文的部分是一樣的
: → a030164851:些字元,所以可能還是必需轉成ASCII Code來試試看!! 11/06 14:49
下面這程式 demo 了兩種轉法的不同
對照一下就可以發現,中文的部分在兩種模式下轉出來的結果是不一樣的
static void Main(string[] args)
{
string tmp_str = "This is a test. 中文測試";
Console.WriteLine("Now printing out '{0}'", tmp_str);
Console.WriteLine("Print use int cast.");
foreach (char c in tmp_str)
{
Console.Write("{0} ", (int)c);
}
Console.WriteLine();
Console.WriteLine("Print use Encoding.ASCII.GetBytes()");
byte[] asc_array = Encoding.ASCII.GetBytes(tmp_str);
foreach (byte b in asc_array)
{
Console.Write("{0} ", b);
}
Console.ReadKey();
}
"This is a test. 中文測試" 這個字串轉出來的結果
Now printing out 'This is a test. 中文測試'
Print use int cast.
84 104 105 115 32 105 115 32 97 32 116 101 115 116 46 32 20013 25991 28204 35430
Print use Encoding.ASCII.GetBytes()
84 104 105 115 32 105 115 32 97 32 116 101 115 116 46 32 63 63 63 63
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.116.82.44