public int IndexOf(string value)
public int IndexOf(string value, int startIndex)
public int IndexOf(string value, int startIndex, int count)
public int IndexOf(char value)
public int IndexOf(char value, int startIndex)
public int IndexOf(char value, int startIndex, int count)
str.indexOf(searchString[, fromIndex])
fromIndex 預設 0,負數視為 0,超過長度視為長度string a = "1,18,33";
bool has1 = a.IndexOf("1") > -1; // true,但其實是匹配到 "18" 的第一個字元
解決:使用正則表達式單詞邊界 `\b`
using System.Text.RegularExpressions;
bool hasExact1 = Regex.IsMatch(a, @"\b1\b"); // false,精確匹配獨立的 "1"
// 通用輔助方法
public static bool ContainsExact(string source, string target)
{
if (string.IsNullOrEmpty(target)) return false;
var escaped = Regex.Escape(target);
return Regex.IsMatch(source, $@"\b{escaped}\b");
}
string s = "abcdef";
int pos = s.IndexOf("c", 3); // 從索引 3 (字元 'd') 開始找,找不到 → -1
// 正確:若想從 'c' 之後找,應用 s.IndexOf("c") + 1
"abc".IndexOf("") // 0
"".IndexOf("") // 0
"abc".IndexOf("", 2) // 2
// 空字串永遠在任意位置「找到」
public static List<int> FindAllIndexes(string source, string target)
{
var list = new List<int>();
int index = 0;
while ((index = source.IndexOf(target, index)) != -1)
{
list.Add(index);
index += target.Length; // 避免重疊匹配
}
return list;
}
// C#:StringComparison.OrdinalIgnoreCase
int pos = s.IndexOf("hello", StringComparison.OrdinalIgnoreCase);
// JS:轉同大小寫後搜尋
var pos = s.toLowerCase().indexOf("hello");
public static int CountOccurrences(string source, string target)
{
if (string.IsNullOrEmpty(target)) return 0;
int count = 0, index = 0;
while ((index = source.IndexOf(target, index, StringComparison.Ordinal)) != -1)
{
count++;
index += target.Length;
}
return count;
}
string url = "https://example.com/path?query=value";
int protoEnd = url.IndexOf("://");
int hostStart = protoEnd + 3;
int pathStart = url.IndexOf('/', hostStart);
string host = url.Substring(hostStart, pathStart - hostStart); // example.com
| 場景 | 推薦做法 | 理由 |
|---|---|---|
| 單次簡單查找 | IndexOf | 原生最快,無額外開銷 |
| 大量重複查找 | 預先建立索引 / Trie / Aho-Corasick | 避免 O(n*m) 重複掃描 |
| 複雜模式匹配 | Regex | 功能強大,但較慢 |
| 不區分大小寫 | IndexOf(..., StringComparison.OrdinalIgnoreCase) | 比 ToLower() + IndexOf 省記憶體 |
| byte[] / Span<byte> 搜尋 | MemoryExtensions.IndexOf (.NET Core 2.1+) | 零複製、高效能 |
IndexOf 是字串查找基石,回傳 0-based 索引,找不到為 -1Regex.IsMatch(@"\b...\b")startIndex 為搜尋起始位置,非「略過前 N 個匹配」