4
A
回答
9
string pattern = "##";
string sentence = "45##78$$#56$$J##K01UU";
IList<int> indeces = new List<int>();
foreach (Match match in Regex.Matches(sentence, pattern))
{
indeces.Add(match.Index);
}
的indeces將有2個,14
3
編輯的代碼,使之成爲清潔的功能。
public IEnumerable<int> FindAllIndexes(string str, string pattern)
{
int prevIndex = -pattern.Length; // so we start at index 0
int index;
while((index = str.IndexOf(pattern, prevIndex + pattern.Length)) != -1)
{
prevIndex = index;
yield return index;
}
}
string str = "45##78$$#56$$JK01UU";
string pattern = "##";
var indexes = FindAllIndexes(str, pattern);
2
你可以通過像這樣使用正則表達式來獲得字符串中模式的所有索引。
string input = "45##78$$#56$$JK01UU", pattern = Regex.Escape("##");
Regex rx = new Regex(pattern);
var indices = new List<int>();
var matches = rx.Matches(s);
for (int i=0 ; i<matches.Length ; i++)
{
indices.Add(matches[i].Index);
}
+0
您可能需要在模式上運行'Regex.Escape()'。 – yamen
+0
@yamen良好的電話謝謝。更新了我的答案。 – McGarnagle
0
另外一個試圖是有效的:
public IEnumerable<int> FindPatternIndexes(string input, string search)
{
var sb = new StringBuilder(input);
for (var i = 0; search.Length <= sb.Length; i++)
{
if (sb.ToString().StartsWith(search)) yield return i;
sb.Remove(0,1);
}
}
0
測試。工作。但有點愚蠢。
string foo = "45##78$$#56$$JK01UU";
char[] fooChar = foo.ToCharArray();
int i = 0;
bool register = false;
foreach (char fc in fooChar)
{
if (fc == '#' && register == true)
{
MessageBox.Show("Index: " + (i-1));
}
else if (fc == '#')
{
register = true;
}
else
{
register = false;
}
i++;
}
相關問題
- 1. 查找字符串中子字符串的所有索引
- 2. 在字符串C++中查找索引
- 3. 查找字符串中所有字符的索引
- 4. 在NSArray中查找一個字符串的所有索引
- 5. 在字符串c中查找單個字符的索引#
- 6. C# - 查找子串的所有索引
- 7. 如何查找字符串中的所有第一個索引?
- 8. 如何查找不同字符串中的所有字符串索引?
- 9. 如何獲取字符串中模式的所有索引?
- 10. C#查找大字符串模式的所有子
- 11. 查找字符串中所有出現的模式的位置
- 12. iOS/Objective-C:查找字符串索引
- 13. 在MATLAB中查找字符串中的字符索引
- 14. 在字符串C#查找模式
- 15. 在長字符串中查找模式?
- 16. Python在字符串中查找模式
- 17. 在字符串中查找模式PHP
- 18. 在C#中查找更大字符串中子字符串的所有位置
- 19. Haskell查找字符串中字符串的索引
- 20. 在字符串中查找某個字符的索引
- 21. 在Python字符串中查找UTF-8字符的索引
- 22. jQuery查找字符串中的模式
- 23. 查找字符串中的模式linux
- 24. 如何找到C中字符串中的字符索引?
- 25. 查找字符串中所有匹配的索引,將搜索詞和索引附加到字典中。
- 26. 找到序列中所有目標字符串的索引
- 27. 在C#字符串中查找報價的所有實例
- 28. 如何在C中查找所有出現的子字符串
- 29. 如何查找列表中具有相同字符串的所有索引?
- 30. 返回ruby中字符串中所有字符的索引
你如何定義一個 「模式」? –
你嘗試過什麼嗎?你有沒有試過正則表達式? – SCB
你能顯示一些輸入字符串和預期的輸出嗎? – Habib