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

C# 字串搜尋完整指南:IndexOf、LastIndexOf、IndexOfAny、LastIndexOfAny 用法與範例

     編輯:ASP.NET 基礎

方法分類總覽

方法用途搜尋方向回傳值
IndexOf尋找字元/子字串第一次出現位置左→右0-based 索引,找不到回傳 -1
LastIndexOf尋找字元/子字串最後一次出現位置右→左0-based 索引,找不到回傳 -1
IndexOfAny尋找字元陣列中任一字元第一次出現位置左→右0-based 索引,找不到回傳 -1
LastIndexOfAny尋找字元陣列中任一字元最後一次出現位置右→左0-based 索引,找不到回傳 -1

一、IndexOf / LastIndexOf 詳細重載

尋找單一字元

int IndexOf(char value)
int IndexOf(char value, int startIndex)
int IndexOf(char value, int startIndex, int count)

尋找子字串

int IndexOf(string value)
int IndexOf(string value, int startIndex)
int IndexOf(string value, int startIndex, int count)

參數說明

  • value:要搜尋的字元或字串
  • startIndex:開始搜尋的索引位置
  • count:從 startIndex 起搜尋的字元數

基本範例

string s = "Hello";
int pos = s.IndexOf('l');        // 2 (第一個 'l')
int pos2 = s.LastIndexOf('l');   // 3 (最後一個 'l')
int pos3 = s.IndexOf("lo");      // 3
int pos4 = s.IndexOf('l', 3);    // 3 (從索引 3 開始找)
int pos5 = s.IndexOf('z');       // -1 (不存在)

二、IndexOfAny / LastIndexOfAny 詳細重載

int IndexOfAny(char[] anyOf)
int IndexOfAny(char[] anyOf, int startIndex)
int IndexOfAny(char[] anyOf, int startIndex, int count)

範例

string s = "Hello";
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };

int firstVowel = s.IndexOfAny(vowels);    // 1 ('e')
int lastVowel = s.LastIndexOfAny(vowels); // 4 ('o')

char[] targets = { 'H', 'e', 'l' };
int first = s.IndexOfAny(targets);    // 0 ('H')
int last = s.LastIndexOfAny(targets); // 3 ('l')

三、實戰應用場景

1. 解析檔案路徑

string path = @"C:\Projects\MyApp\bin\Debug\app.exe";
int lastSlash = path.LastIndexOf('\\');
string folder = path.Substring(0, lastSlash);   // C:\Projects\MyApp\bin\Debug
string file = path.Substring(lastSlash + 1);    // app.exe

2. 檢查字串是否包含任一關鍵字

string input = "用戶輸入的內容";
char[] forbidden = { '<', '>', '&', '"', '\'' };
bool hasForbidden = input.IndexOfAny(forbidden) >= 0;

3. 切割字串(手動 Split)

string data = "apple,banana,orange";
var list = new List<string>();
int start = 0;
while (true)
{
    int comma = data.IndexOf(',', start);
    if (comma < 0) { list.Add(data.Substring(start)); break; }
    list.Add(data.Substring(start, comma - start));
    start = comma + 1;
}

4. 移除字串尾部特定字元

string s = "Hello World!!!";
char[] trimChars = { '!', ' ', '\t' };
int lastGood = s.LastIndexOfAny(trimChars);
string cleaned = (lastGood < 0) ? s : s.Substring(0, lastGood + 1);

四、效能與注意事項

  • 區分大小寫:所有方法預設區分大小寫,需不區分時請先 `.ToLower()` 或 `.ToUpper()`
  • 空字串行為:`"abc".IndexOf("")` 回傳 0;`"".IndexOf("a")` 回傳 -1
  • startIndex 越界:大於字串長度會拋出 `ArgumentOutOfRangeException`
  • 效能提示:單字元搜尋比子字串快;大量搜尋考慮 `StringBuilder` 或 `Regex`
  • 文化特性:預設使用序數比較,若需語言敏感比較請用 `CompareInfo.IndexOf`

五、JavaScript 對應方法

// JS 相對應方法
str.indexOf(searchValue, fromIndex)      // 對應 IndexOf
str.lastIndexOf(searchValue, fromIndex)  // 對應 LastIndexOf
// JS 無直接 IndexOfAny,需自行實作或用 Regex
// 例:str.search(/[aeiou]/) 找第一個母音

總結

掌握這四組方法的重載差異、搜尋方向與回傳值語意,能大幅簡化字串處理邏輯。記住:IndexOf 找第一個、LastIndexOf 找最後一個、Any 系列找字元集合中的任一個,配合 startIndex/count 參數即可精準控制搜尋範圍。

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