首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

VB 函數對照 C# 完整指南:InStr、Mid 等字串操作對應表

     編輯:程式設計綜合問答

遷移必備:VB 字串函數對應 C# 寫法

從 VB.NET 遷移至 C# 時,字串處理函數的對應關係是開發者最常查詢的內容。本文整理核心函數對照表,並提供自訂擴充方法範例。

核心函數對照表

VB 函數C# 對應說明
InStrString.IndexOf回傳子字串首次出現位置(0 起始)
InStrRevString.LastIndexOf回傳子字串最後出現位置
MidString.Substring擷取指定長度的子字串
LeftString.Substring(0, length)取左側指定長度字串
RightString.Substring(str.Length - length)取右側指定長度字串
LenString.Length取得字串長度
TrimString.Trim移除首尾空白字元
ReplaceString.Replace字串替換
SplitString.Split分割字串為陣列
JoinString.Join陣列合併為字串

自訂 VB 風格擴充方法

為保持程式碼風格一致,可建立靜態類別封裝 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"

注意事項

  • C# 索引從 0 開始,VB 從 1 起始,轉換時需加減 1
  • C# 字串為不可變型別,所有操作都會產生新字串
  • 大小寫比較預設區分大小寫,需指定 StringComparison.OrdinalIgnoreCase

掌握對應關係並善用擴充方法,VB 遷移 C# 字串處理將更加順暢。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved