- .NET Framework : 4.7.2
- IDE : Visual Studio Community 2019
- OS : Windows 10 x64
- typesetting : Markdown
第一种方法
code
using System;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
string str = "1aqw5a7a9a";
// a的索引值是1,5,7,9
// 建立一个存储a的索引值的数组
int[] index = new int[str.Length];
int j = 0;
index[j++] = str.IndexOf('a');
for (int i = str.IndexOf('a') + 1; i <= str.LastIndexOf('a'); i++)
{
i = str.IndexOf('a', i);
index[j++] = i;
}
sw.Stop();
Console.WriteLine("该方法用时:" + sw.Elapsed);
foreach (var item in index)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
result
该方法用时:00:00:00.0000138
1
5
7
9
0
0
0
0
0
0
第二种方法 - 网友的解法
- [ 参考 ]http://zhidao.baidu.com/link?url=Zyw54OTIS8FH4tOUDG8VUSC2SiqkL7b1unCp_8wVHcBr6hGGRpw7YjYksg2JCfsZzX9wzHplWwLlMC-d22qcya
code
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
ArrayList lt = new ArrayList();
string str = "sfskjfskfakfjaga";
int index = 0;
foreach (Char ch in str)
{
if (ch == 's')
{
lt.Add(index);
}
index++;
}
sw.Stop();
Console.WriteLine("该方法用时:" + sw.Elapsed);
Console.ReadKey();
}
}
}
result
该方法用时:00:00:00.0000332
第三种方法 - 思考与优化
code
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
string str = "1aqw5a7a9a";
// a的索引值是1,5,7,9
var index = new ArrayList();
// 建立一个存储a的索引值的链表
index.Add(str.IndexOf('a'));
for (int i = str.IndexOf('a') + 1; i <= str.LastIndexOf('a'); i++)
{
i = str.IndexOf('a', i);
index.Add(i);
}
sw.Stop();
Console.WriteLine("该方法用时:" + sw.Elapsed);
foreach (var item in index)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
result
该方法用时:00:00:00.0000410
1
5
7
9
more knowledge
- 1 使用Stopwatch计算代码运行的时间,虽然可以这样做,但是不推荐。因为有专门的测试工具。
- 2 同一个问题,不同的解法。有最优,也有最适合。
resource
- [文档] docs.microsoft.com/zh-cn/dotnet/csharp
- [规范] github.com/dotnet/docs/tree/master/docs/standard/design-guidelines
- [源码] referencesource.microsoft.com
- [ IDE ] visualstudio.microsoft.com/zh-hans
- [.NET Core] dotnet.github.io
感恩曾经帮助过 心少朴 的人。
C#优秀,值得学习。.NET Core具有跨平台的能力,值得关注。
Console,WinForm,WPF,ASP.NET,Azure WebJob,WCF,Unity3d,UWP可以适当地了解。
注:此文是自学笔记所生,质量中下等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。