求助,关于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()); } else { List<string> lPos = new List<string>(); lPos.Add(i.ToString()); dic.Add(s, lPos); } }; foreach (string s in dic.Keys) { List<string> l = (List<string>)dic[s]; if(l.Count>1) { Console.WriteLine("{0}:{1}",s,String.Join(",",l.ToArray())); } }
[解决办法]
[code=C#][/code]public List<int> getIndex(string[] str, string s)
{
List<int> list2 = new List<int>();
for (int i = 0; i < str.Length; ++i)
{
if (str[i] == s)
{
list2.Add(i);
}
}
if (list2.Count == 0)
{
list2.Add(-1);
}
return list2;
}
static void Main(string[] args)
{
Hashtable dic = new Hashtable();
dic.
Program p = new Program();
int c = p.GetHashCode();
Console.WriteLine(c);
string[] b = { "一", "七", "一", "三", "四", "五", "二", "六", "三", "四", "一" };
string a = "一";
List<int> newL = new Program().getIndex(b, a);
if (newL[0] != -1)
{
Console.Write("值:" + a + " 所在数组中位置: ");
foreach (int i in newL)
{
Console.Write("{0} ", i);
}
}
else Console.WriteLine("b中没有a");