查找字符串为"xy"
依次返回每个xy的起始位置(0起):2, 7, 13
7 个解决方案
#2
KMP算法!
#3
简单写了个
String str ="acxyefdxycrtsxyf";
String target = "xy";
while (true)
{
int sta = str.IndexOf(target, startIndex);
if (sta == -1)
{
break;
}
lst.Add(sta);
startIndex = sta + target.Length;
}
String str ="acxyefdxycrtsxyf";
String target = "xy";
while (true)
{
int sta = str.IndexOf(target, startIndex);
if (sta == -1)
{
break;
}
lst.Add(sta);
startIndex = sta + target.Length;
}
#4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSDN_Help
{
class Program
{
static void Main(string[] args)
{
string res = "acxyefdxycrtsxyf";
string des = "xy";
char[] TempSpace=new Char[2];
for (int i = 0; i <= res.Length - des.Length; i++)
{
res.CopyTo(i, TempSpace, 0, des.Length);
if (new string(TempSpace).Equals(des))
{
Console.WriteLine(i);
}
}
}
}
}
当然如果要追求算法的效率,可以看看KMP算法。
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSDN_Help
{
class Program
{
static void Main(string[] args)
{
string res = "acxyefdxycrtsxyf";
string des = "xy";
char[] TempSpace=new Char[2];
for (int i = 0; i <= res.Length - des.Length; i++)
{
res.CopyTo(i, TempSpace, 0, des.Length);
if (new string(TempSpace).Equals(des))
{
Console.WriteLine(i);
}
}
}
}
}
当然如果要追求算法的效率,可以看看KMP算法。
#5
对了,用IndexOf更方便些~~
#6
int[] list = Regex.Matches("acxyefdxycrtsxyf", "xy").OfType<Match>().Select(t => t.Index).ToArray();
#7
4楼和6楼的答案让人感慨正则表达式和lambda表达式的威力!
#1
可以自己遍历查找,或者
http://blog.csdn.net/bdmh/article/details/6090983里面有c#代码
#2
KMP算法!
#3
简单写了个
String str ="acxyefdxycrtsxyf";
String target = "xy";
while (true)
{
int sta = str.IndexOf(target, startIndex);
if (sta == -1)
{
break;
}
lst.Add(sta);
startIndex = sta + target.Length;
}
String str ="acxyefdxycrtsxyf";
String target = "xy";
while (true)
{
int sta = str.IndexOf(target, startIndex);
if (sta == -1)
{
break;
}
lst.Add(sta);
startIndex = sta + target.Length;
}
#4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSDN_Help
{
class Program
{
static void Main(string[] args)
{
string res = "acxyefdxycrtsxyf";
string des = "xy";
char[] TempSpace=new Char[2];
for (int i = 0; i <= res.Length - des.Length; i++)
{
res.CopyTo(i, TempSpace, 0, des.Length);
if (new string(TempSpace).Equals(des))
{
Console.WriteLine(i);
}
}
}
}
}
当然如果要追求算法的效率,可以看看KMP算法。
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSDN_Help
{
class Program
{
static void Main(string[] args)
{
string res = "acxyefdxycrtsxyf";
string des = "xy";
char[] TempSpace=new Char[2];
for (int i = 0; i <= res.Length - des.Length; i++)
{
res.CopyTo(i, TempSpace, 0, des.Length);
if (new string(TempSpace).Equals(des))
{
Console.WriteLine(i);
}
}
}
}
}
当然如果要追求算法的效率,可以看看KMP算法。
#5
对了,用IndexOf更方便些~~
#6
int[] list = Regex.Matches("acxyefdxycrtsxyf", "xy").OfType<Match>().Select(t => t.Index).ToArray();
#7
4楼和6楼的答案让人感慨正则表达式和lambda表达式的威力!