【发布时间】:2014-06-23 12:25:42
【问题描述】:
输入是一个字符串和一个字符,即:
string stInput = "An string with multiple spaces";
char charInput = ' ';
输出应该是一个整数数组,即:
int[] output = CharPositions(stInput, charInput);
// output = {2, 9, 14, 23};
这是我的猜测:
int[] CharPositions(string stInput, char charInput)
{
List<int> output = new List<int>();
int i = stInput.IndexOf(charInput, 0);
while(i > -1)
{
output.Add(i);
i = stInput.IndexOf(charInput, i + 1);
}
output.Add(i);
return output.ToArray();
}
有没有更高效的方法?
【问题讨论】:
-
你有没有尝试过,或者你只是期待一个答案?
-
@Delta 我已经尝试过使用 string.IndexOfAny() 但它却相反。在与遇到相同问题的人进行谷歌搜索后,我什么也没找到。
-
很难猜测一种低效的方式可能是什么样子。
-
你需要付出更多的努力。你试过什么?这读起来像“请发送代码”
-
我在笔记本上写了一个简单的循环,但看起来不太好。我会照你的要求复制它。
标签: c# regex string char comparison