從 VB.NET 遷移至 C# 時,字串處理函數的對應關係是開發者最常查詢的內容。本文整理核心函數對照表,並提供自訂擴充方法範例。
| VB 函數 | C# 對應 | 說明 |
|---|---|---|
| InStr | String.IndexOf | 回傳子字串首次出現位置(0 起始) |
| InStrRev | String.LastIndexOf | 回傳子字串最後出現位置 |
| Mid | String.Substring | 擷取指定長度的子字串 |
| Left | String.Substring(0, length) | 取左側指定長度字串 |
| Right | String.Substring(str.Length - length) | 取右側指定長度字串 |
| Len | String.Length | 取得字串長度 |
| Trim | String.Trim | 移除首尾空白字元 |
| Replace | String.Replace | 字串替換 |
| Split | String.Split | 分割字串為陣列 |
| Join | String.Join | 陣列合併為字串 |
為保持程式碼風格一致,可建立靜態類別封裝 VB 風格方法:
public static class VbStringExtensions
{
// InStr 從 1 起始,找不到回傳 0
public static int InStr(this string source, string value, int startIndex = 1)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(value)) return 0;
if (startIndex < 1) startIndex = 1;
int idx = source.IndexOf(value, startIndex - 1, StringComparison.Ordinal);
return idx >= 0 ? idx + 1 : 0;
}
// Mid 從 1 起始計算位置
public static string Mid(this string source, int start, int length = -1)
{
if (string.IsNullOrEmpty(source) || start < 1) return string.Empty;
int realStart = start - 1;
if (realStart >= source.Length) return string.Empty;
return length < 0 ? source.Substring(realStart) : source.Substring(realStart, Math.Min(length, source.Length - realStart));
}
}
string text = "Hello World";
int pos = text.InStr("World"); // 回傳 7
string sub = text.Mid(7, 5); // 回傳 "World"
StringComparison.OrdinalIgnoreCase掌握對應關係並善用擴充方法,VB 遷移 C# 字串處理將更加順暢。