读书人

牛人哪位高手能解答 string[]数组和st

发布时间: 2013-02-15 15:46:56 作者: rapoo

牛人谁能解答 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;
}

目前这样尝试着实现了一下。。可能有点麻烦,不过功能貌似实现了,不知道是不是LZ需要的。
[解决办法]
引用:
这个写的转换成2进制的 还是有点不太明白。"a","b","c","e","ab","ac","abe"转换出的2进制结果能和"ac" 二进制结果对比 得出 "a","c","ac"吗


class Program
{
static void Main(string[] args)
{

string[] s1={"a","b","c","d","e","f","h","ab","bc","abf","eh","bh","bcf","ch"};
string s2= "cbeh";



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;
}
}

读书人网 >asp.net

热点推荐