| 方法 | 用途 | 搜尋方向 | 回傳值 |
|---|---|---|---|
| IndexOf | 尋找字元/子字串第一次出現位置 | 左→右 | 0-based 索引,找不到回傳 -1 |
| LastIndexOf | 尋找字元/子字串最後一次出現位置 | 右→左 | 0-based 索引,找不到回傳 -1 |
| IndexOfAny | 尋找字元陣列中任一字元第一次出現位置 | 左→右 | 0-based 索引,找不到回傳 -1 |
| LastIndexOfAny | 尋找字元陣列中任一字元最後一次出現位置 | 右→左 | 0-based 索引,找不到回傳 -1 |
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 (不存在)
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')
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
string input = "用戶輸入的內容";
char[] forbidden = { '<', '>', '&', '"', '\'' };
bool hasForbidden = input.IndexOfAny(forbidden) >= 0;
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;
}
string s = "Hello World!!!";
char[] trimChars = { '!', ' ', '\t' };
int lastGood = s.LastIndexOfAny(trimChars);
string cleaned = (lastGood < 0) ? s : s.Substring(0, lastGood + 1);
// JS 相對應方法
str.indexOf(searchValue, fromIndex) // 對應 IndexOf
str.lastIndexOf(searchValue, fromIndex) // 對應 LastIndexOf
// JS 無直接 IndexOfAny,需自行實作或用 Regex
// 例:str.search(/[aeiou]/) 找第一個母音
掌握這四組方法的重載差異、搜尋方向與回傳值語意,能大幅簡化字串處理邏輯。記住:IndexOf 找第一個、LastIndexOf 找最後一個、Any 系列找字元集合中的任一個,配合 startIndex/count 參數即可精準控制搜尋範圍。