在 Web 應用程式中透過 QueryString 傳遞中文參數時,需正確編碼與解碼以避免亂碼。
<system.web>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="zh-TW"
fileEncoding="utf-8" />
</system.web>
現代專案建議統一使用 UTF-8,而非舊式的 gb2312。
// 傳遞端
string name = "中文參數";
string url = "B.aspx?Name=" + Server.UrlEncode(name); // 或 HttpUtility.UrlEncode
Response.Redirect(url);
// 接收端
string name = Request.QueryString["Name"];
string decoded = Server.UrlDecode(name); // 或 HttpUtility.UrlDecode
<script>
function GoUrl() {
var name = "中文參數";
// 使用 encodeURIComponent 而非 escape (已淘汰)
location.href = "B.aspx?Name=" + encodeURIComponent(name);
}
</script>
注意:若透過 JavaScript 呼叫 Web Service 傳遞中文,web.config 設定可能不生效,必須在前端明確編碼,後端解碼。
string input = "123456789";
// 方法一:ToString 自訂格式 (最語意化)
string result1 = long.Parse(input).ToString("##-###-####"); // "12-345-6789"
// 方法二:Insert 插入字元 (需注意索引位置)
string result2 = input.Insert(2, "-").Insert(6, "-"); // 先插後面再插前面,索引不受影響
// 方法三:Regex 正則替換 (彈性最高)
var regex = new Regex(@"^(\d{2})(\d{3})(\d{4})$");
string result3 = regex.Replace(input, "$1-$2-$3");
string s = "123456789";
int pos1 = 3, pos2 = 6; // 0-based 索引
// 方法一:Remove + Insert (直觀但建立多個字串物件)
char c1 = s[pos1], c2 = s[pos2];
s = s.Remove(pos1, 1).Insert(pos1, c2.ToString())
.Remove(pos2, 1).Insert(pos2, c1.ToString());
// 方法二:XOR 交換演算法 (無需暫存變數,展示位運算技巧)
char[] arr = s.ToCharArray();
arr[pos1] = (char)(arr[pos1] ^ arr[pos2]);
arr[pos2] = (char)(arr[pos1] ^ arr[pos2]);
arr[pos1] = (char)(arr[pos1] ^ arr[pos2]);
s = new string(arr);
// 方法三:陣列暫存交換 (最清晰、效能佳)
char[] chars = s.ToCharArray();
char temp = chars[pos1];
chars[pos1] = chars[pos2];
chars[pos2] = temp;
s = new string(chars);
// 方法四:Regex 替換 (適合複雜模式)
if (pos1 > pos2) { var t = pos1; pos1 = pos2; pos2 = t; }
string pattern = $"^(.{{{pos1}}})(.)(.{{{pos2 - pos1 - 1}}})(.)(.*)$";
s = Regex.Replace(s, pattern, "$1$4$3$2$5");
var rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine(rnd.Next() % 10); // 輸出 0-9
// 老寫法
string s1 = "AAAAAAAAAAAAAAAAAAAAA"; // 21 個 A
// 新寫法:使用 string 建構子 (效能最佳、可讀性高)
string s2 = new string('A', 21);
string.CompareTo:實作 IComparable,用於實例方法排序。string.Compare:靜態方法,支援文化特性、忽略大小寫等進階選項。string.Compare(strA, strB, StringComparison.Ordinal) 明確指定比較規則。HttpUtility.UrlEncode/UrlDecode,前端用 encodeURIComponent。ToString("format"),複雜模式用 Regex。ToCharArray 陣列操作,平衡效能與可讀性。StringBuilder 避免頻繁記憶體配置。