例如:
byte [] a = new byte[5];
byte [] b = new byte[2];
a[0] = 5;
a[1] = 2;
a[2] = 3;
a[3] = 6;
a[4] = 1;b[0] = 3;
b[1] = 6;
现在要找出b在a里的起始位置(起始位置应该是2)。当然转换成string很方便,但是如果数据组很大效率不高,现在就是想知道或实现有直接类似于string.IndexOf之类的方法?
byte [] a = new byte[5];
byte [] b = new byte[2];
a[0] = 5;
a[1] = 2;
a[2] = 3;
a[3] = 6;
a[4] = 1;b[0] = 3;
b[1] = 6;
现在要找出b在a里的起始位置(起始位置应该是2)。当然转换成string很方便,但是如果数据组很大效率不高,现在就是想知道或实现有直接类似于string.IndexOf之类的方法?
首先设置2个虚拟指针分别指向a,b的头部之前的空位(a[-1]位置),然后a指针顺次下移,每次下移,b指针也下移,若这时a指针值=b指针值,则建立临时指针a2,指向a指针的下一个位置,并把b指针下移,然后继续比较和下移a2和b,直到b结束,如果都相符则返回a指针的位置,即为所需的值;如果出现不相符,则释放a2指针的资源,复位b指针到-1值,然后继续下移a指针,重复上述操作。可能叙述的不是很清楚,呵呵,实际上就是2个嵌套的循环。
using System;
public class SamplesArray { public static void Main() { // Creates and initializes a new Array with three elements of the same value.
Array myArray=Array.CreateInstance( typeof(String), 12 );
myArray.SetValue( "the", 0 );
myArray.SetValue( "quick", 1 );
myArray.SetValue( "brown", 2 );
myArray.SetValue( "fox", 3 );
myArray.SetValue( "jumps", 4 );
myArray.SetValue( "over", 5 );
myArray.SetValue( "the", 6 );
myArray.SetValue( "lazy", 7 );
myArray.SetValue( "dog", 8 );
myArray.SetValue( "in", 9 );
myArray.SetValue( "the", 10 );
myArray.SetValue( "barn", 11 ); // Displays the values of the Array.
Console.WriteLine( "The Array contains the following values:" );
PrintIndexAndValues( myArray ); // Searches for the first occurrence of the duplicated value.
String myString = "the";
int myIndex = Array.IndexOf( myArray, myString );
Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex ); // Searches for the first occurrence of the duplicated value in the last section of the Array.
myIndex = Array.IndexOf( myArray, myString, 4 );
Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex ); // Searches for the first occurrence of the duplicated value in a section of the Array.
myIndex = Array.IndexOf( myArray, myString, 6, 5 );
Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );
}
public static void PrintIndexAndValues( Array myArray ) {
for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
}
}
/*
This code produces the following output.The Array contains the following values:
[0]: the
[1]: quick
[2]: brown
[3]: fox
[4]: jumps
[5]: over
[6]: the
[7]: lazy
[8]: dog
[9]: in
[10]: the
[11]: barn
The first occurrence of "the" is at index 0.
The first occurrence of "the" between index 4 and the end is at index 6.
The first occurrence of "the" between index 6 and index 10 is at index 6.
*/
用Array.IndexOf 方法 查找出b[x]在a中的索引位置当然没问题了。
偶是想在a中找整个的b所在a中的索引,而不是b[x]。如果用Array.IndexOf 配合循环是能实现,但是偶在想.net本身有没有实现在这样
功能方法?有的话,这样方便一些啊