日期:2014-05-18  浏览次数:20875 次

求助,关于String[]求重复值的算法
string[] b = { "一", "七", "一", "三", "四","五","二", "六", "三", "四","一"};

怎么样得到值与该值所有对应位置

值:一 所在数组中位置:0,2,10

值:三 所在数组中位置:0,2

值:四 所在数组中位置:4,9

------解决方案--------------------
C# code

            string[] b = { "一", "七", "一", "三", "四", "五", "二", "六", "三", "四", "一" };
            Dictionary<string, List<int>> dic = new Dictionary<string, List<int>>();
            for (int i = 0; i < b.Length; i++)
            {
                if (dic.ContainsKey(b[i]))
                    dic[b[i]].Add(i);
                else
                {
                    List<int> list = new List<int>();
                    list.Add(i);
                    dic.Add(b[i], list);
                }
            }
            foreach (string s in dic.Keys)
            {
                Console.Write(s + ":");
                foreach (int i in dic[s])
                    Console.Write(i + " ");
                Console.WriteLine();
            }
/*
输出:
一:0 2 10
七:1
三:3 8
四:4 9
五:5
二:6
六:7
*/

------解决方案--------------------
C# code

       private void button1_Click(object sender, EventArgs e)
        {            
            string[] b = { "一", "七", "一", "三", "四", "五", "二", "六", "三", "四", "一" };
            string returnValue =GetIndex(b, "一");            
        }

        public string GetIndex(string[] b,string value)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] == value)
                {
                    sb.Append(",");
                    sb.Append(i);                    
                }
            }
            return sb.ToString().Substring(1);
        }

------解决方案--------------------
string[] b = { "一", "七", "一", "三", "四", "五", "二", "六", "三", "四", "一" };
Dictionary<string, List<int>> dic = new Dictionary<string, List<int>>();
for (int i = 0; i < b.Length; i++)
{
if (dic.ContainsKey(b[i]))
dic[b[i]].Add(i);
else
{
List<int> list = new List<int>();
list.Add(i);
dic.Add(b[i], list);
}
}
foreach (string s in dic.Keys)
{
Console.Write(s + ":");
foreach (int i in dic[s])
Console.Write(i + " ");
Console.WriteLine();
}
/*
输出:
一:0 2 10
七:1
三:3 8
四:4 9
五:5
二:6
六:7
*/

------
漂亮!
------解决方案--------------------
HashTable可以直接用索引访问,应该快点
C# code
 string[] b = { "一", "七", "一", "三", "四", "五", "二", "六", "三", "四", "一" };
        Hashtable dic = new Hashtable();
        for(int i=0;i<b.Length;i++)
        {

            string s = b[i];
            if (dic[s] != null)
            {
                ((List<string>)dic[s]).Add(i.ToString());