您的位置:首页 > 编程语言 > C#

C#控制台基础 找到一个字符串中一个字符的所有索引值

2016-09-05 19:00 429 查看
       慈心积善融学习,技术愿为有情学。善心速造多好事,前人栽树后乘凉。我今于此写经验,愿见文者得启发。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
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();
}
}
}




然后在网络上,有个算法,网址:http://zhidao.baidu.com/link?url=Zyw54OTIS8FH4tOUDG8VUSC2SiqkL7b1unCp_8wVHcBr6hGGRpw7YjYksg2JCfsZzX9wzHplWwLlMC-d22qcya

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();

ArrayList lt = new System.Collections.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();
}
}
}




呐,看到了木,嘿嘿。算法的不同,处理的速度不同。

参考了网络上的方法,我自己更改了代码,

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
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();
}
}
}




使用链表更加优秀!

果然呀,出来写代码,必须见多识广。

感恩曾经帮助过 心少朴 的人。

C#优秀,值得学习。Console,ASP.NET,Winform,WPF,设计模式等都可以关注一下,眼界要开阔。

Visual Studio IDE很好用,推荐!
注:此文是自学笔记所生,质量中等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐