牛人谁能解答 string[]数组和string的问题
有个数组 string[] s1={"a","b","c","d","e","f","h","ab","bc","abf","eh","bh","bcf","ch"}
还有一个 string s2= "cbeh"
想得到的结果是数组 s3={"b","c","e","h","bc","bh","eh","bh","ch"}
这个数组s1和s2的值都是变化的也有可能是其他值,但规则是这样的。
就是想得到s1中包含s2中的数组。s2的值不一定是按a-z的顺序排列
这个我实在想不出有什么好办法,之前用了s1.Where(i => s2.Contains(i)) 但是遇到数据不连续的就失效了
谢谢~~
[解决办法]
static void Main(string[] args)
{
string[] s1 = { "a", "b", "c", "d", "e", "f", "h", "ab", "bc", "abf", "eh", "bh", "bcf", "ch" };
string s2 = "cbeh";
foreach (string s in s1)
{
if (IsVal(s, s2))
System.Console.WriteLine(s);
}
System.Console.Read();
}
private static bool IsVal(string s,string str)
{
bool result = true;
for (int i = 0; i < s.Length; i++)
{
//System.Console.WriteLine(s.Substring(i, 1));
if (str.IndexOf(s.Substring(i, 1)) < 0)
result = false;
}
return result;
}
List<string> resultList=GetResult(s2,s1);
string resultString=null;
for(int i=0;i<resultList.Count;i++)
{
resultString+=resultList[i]+",";
}
Console.WriteLine(resultString);
Console.ReadKey();
}
static List<string> GetResult(string s2, string[] s1)
{
List<string> resultList = new List<string>();
//先初步过滤长度比s2大的字符串
List<string> newS1=new List<string>();
for(int i=0;i<s1.Length;i++)
{
if(s1[i].Length<s2.Length)
{
newS1.Add(s1[i]);
}
}
int num2=GetNum(s2);
int itemNum=0;
for(int i=0;i<newS1.Count;i++)
{
itemNum=GetNum(s1[i]);
if((itemNum & num2)==itemNum)
{
resultList.Add(s1[i]);
}
}
return resultList;
}
static int GetNum(string s) //把字符串成位串一共26位,从低位到高位依次标识字符(a-z)是否在字符串中
{
int n = 0;//4个字节=32位
char aChar;
char constChar='a';
int t=1;
int position=0; //字符和'a'的差为k,根据映射规则,说明2进制数的
//从低位算起的第(k+1)位上为1,对应的整数为2的k次方;
for(int i=0;i<s.Length;i++)
{
aChar=s[i];
position=(aChar-constChar);
n+=(int)Math.Pow(2,position);
}
return n;
}
}