首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 字串操作進階技巧與最佳實踐(二):URL 編碼、格式化、字元交換與效能優化

     編輯:關於C#

1. URL 傳遞中文參數完整解決方案

在 Web 應用程式中透過 QueryString 傳遞中文參數時,需正確編碼與解碼以避免亂碼。

方法一:設定 web.config 全域化(推薦)

<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

方法三:前端 JavaScript 編碼(HTML 頁面跳轉)

<script>
function GoUrl() {
    var name = "中文參數";
    // 使用 encodeURIComponent 而非 escape (已淘汰)
    location.href = "B.aspx?Name=" + encodeURIComponent(name);
}
</script>
注意:若透過 JavaScript 呼叫 Web Service 傳遞中文,web.config 設定可能不生效,必須在前端明確編碼,後端解碼。

2. 將數字字串格式化為 12-345-6789 三種方法

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");

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");

4. 實用小技巧集錦

% 運算子取隨機個位數


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);

字串比較:CompareTo vs Compare

  • string.CompareTo:實作 IComparable,用於實例方法排序。
  • string.Compare:靜態方法,支援文化特性、忽略大小寫等進階選項。
  • 實務上推薦使用 string.Compare(strA, strB, StringComparison.Ordinal) 明確指定比較規則。

總結建議

  • URL 編碼統一使用 HttpUtility.UrlEncode/UrlDecode,前端用 encodeURIComponent。
  • 格式化數字優先用 ToString("format"),複雜模式用 Regex。
  • 字元交換首選 ToCharArray 陣列操作,平衡效能與可讀性。
  • 大量字串操作考慮 StringBuilder 避免頻繁記憶體配置。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved