【发布时间】:2016-09-10 09:38:39
【问题描述】:
我在想短字符串是否具有字符值的好方法。就像 A = 0,B = 1...
我编写了一些代码,但最好的答案是错误的,我想我知道问题出在哪里,但我不知道问题出在哪里。
代码如下:
void Start()
{
i = Inventory.instance;
List<Items> items = i.returnList("Food");
Debug.Log(items.Count); List<Items> sItems = GetListSetList(items);
foreach (Items item in sItems)
{
Debug.Log(item.name);
}
}
列表项 = i.returnList ("食物");
public List<Items> returnList(string tag)
{
List<Items> classifiedItemSet = new List<Items>();
foreach (Items i in items)
{
if (i.tag == tag)
{
classifiedItemSet.Add(i);
}
}
return classifiedItemSet;
}
List sItems = GetListSetList (items);
private List<Items> GetListSetList(List<Items> itemS)
{
foreach (Items item in itemS)
{
GetAlphabetaValue(item);
}
List<Items> shorted = new List<Items>();
Items[] hold = new Items[itemS.Count];
foreach (Items item in itemS)
{
for (int x = 0; x < hold.Length; x++)
{
if (hold[x] == null)
{
hold[x] = item;
break;
}
else
{
bool PassIt = true;
for (int c_value = 0; c_value < item.Alphabet_value.Length; c_value++)
if (item.Alphabet_value[c_value] > hold[x].Alphabet_value[c_value])
PassIt = false;
if (PassIt)
{
for (int h_pos = hold.Length - 1; h_pos > x; h_pos--)
if (hold[h_pos] != null)
hold[h_pos] = hold[h_pos - 1];
hold[x] = item;
break; // If i use this break i get error ("NullReferenceException")
}
else continue;
}
}
}
for (int x = 0; x < hold.Length; x++)
shorted.Add(hold[x]);
return shorted;
}
这个 void 的开始我给每个项目名称字符串中的每个字符一些值。就是这部分:GetAlphabetaValue (item);哦,抱歉将其命名为 AlphaBeta :) 好吧,我是如何得到这个值的:
private void GetAlphabetaValue(Items x)
{
x.Alphabet_value = new int[x.name.Length];
for (int c = 0; c < x.Alphabet_value.Length; c++)
{
string character = x.name.Substring(c, 1);
character.ToLower();
switch (character)
{
case "a":
x.Alphabet_value[c] = 0;
break;
case "b":
x.Alphabet_value[c] = 1;
break;
case "c":
x.Alphabet_value[c] = 2;
break;
case "d":
x.Alphabet_value[c] = 3;
break;
case "e":
x.Alphabet_value[c] = 4;
break;
case "f":
x.Alphabet_value[c] = 5;
break;
//To the end
}
}
}
我希望你能理解我想要说的 :D 谢谢 :) 在我开始这样做之前,我会尝试在互联网上查找一些信息,但我没有找到任何真正可以从数组中缩短多个字符串的信息。
这部分我认为我错了,但现在我看不出有什么问题:
for (int h_pos = hold.Length - 1; h_pos > x; h_pos--)
if (hold [h_pos] != null)
{
hold [h_pos] = hold [h_pos - 1];
hold [x] = item;
}
【问题讨论】:
标签: c# arrays string short alphabetical-sort