如果字符串中有一个或多个字符反复出现。就像在下面的字符串中一样:
1+1+1-2+2/2*4-2*3/23
现在在上面的字符串中,在索引处的出现+
次数和在其他索引处的出现次数,然后将它们存储在二维数组中所以现在的问题是如何做到这一点。3
1,3,7
-
2
5,13
以下函数将返回给定搜索字符串的所有匹配索引:
List<int> GetAllIndices(string input, string search)
{
List<int> result = new List<int>();
int index = input.IndexOf(search);
while(index != -1)
{
result.Add(index);
index++;//increment to avoid matching the same index again
if(index >= input.Length)//check if index is greater than string (causes exception)
break;
index = input.IndexOf(search, index);
}
return result;
}
它还应该处理重叠匹配,例如:搜索"iii"
出现的"ii"
将返回[0,1]
如果您想使用此函数创建符号列表及其索引,那么我会推荐以下方法:
string input = "1+1+1-2+2/2*4-2*3/23";
//create a dictionary to store the results
Dictionary<string, List<int>> results = new Dictionary<string, List<int>>();
//add results for + symbol
results.Add("+", GetAllIndices(input, "+"));
//add results for - symbol
results.Add("-", GetAllIndices(input, "-"));
//you can then access all indices for a given symbol like so
foreach(int index in results["+"])
{
//do something with index
}
您甚至可以更进一步,将其包装在一个搜索多个符号的函数中:
Dictionary<string, List<int>> GetSymbolMatches(string input, params string[] symbols)
{
Dictionary<string, List<int>> results = new Dictionary<string, List<int>>();
foreach(string symbol in symbols)
{
results.Add(symbol, GetAllIndices(input, symbol));
}
return results;
}
然后您可以像这样使用它:
string input = "1+1+1-2+2/2*4-2*3/23";
Dictionary<string, List<int>> results = GetSymbolMatches(input, "+", "-", "*", "/");
foreach(int index in results["+"])
{
//do something with index
}
使用 Linq:
var allIndices = yourString.Select((c, i) => new { c, i, })
.Where(a => a.c == '+').Select(a => a.i);
获取包含字符串中所有字符的字典,例如:
var allCharsAllIndices = yourString.Select((c, i) => new { c, i, })
.GroupBy(a => a.c)
.ToDictionary(g => g.Key, g => g.Select(a => a.i).ToArray());
简单=最好。没有内存分配。
public static IEnumerable<int> GetIndexOfEvery(string haystack, string needle)
{
int index;
int pos = 0;
string s = haystack;
while((index = s.IndexOf(needle)) != -1)
{
yield return index + pos;
pos = pos + index + 1;
s = haystack.Substring(pos);
}
}
你可以通过改变“价值”来尝试这个
var duplicates = param1.ToCharArray().Select((item, index) => new { item, index })
.Where(x =>x.item==VALUE).GroupBy(g=>g.index)
.Select(g => new { Key = g.Key })
.ToList();
string msg = "1+1+1-2+2/2*4-2*3/23";
Dictionary<char, List<int>> list = new Dictionary<char, List<int>>();
for (int i = 0; i < msg.Length; i++)
{
if (!list.ContainsKey(msg[i]))
{
list.Add(msg[i], new List<int>());
list[msg[i]].Add(i);
}
else
list[msg[i]].Add(i);
}