-2

我有一个 long[] 类型的数组,其中包含 19 组数字,然后是另一个 char[] 类型的数组,当用户输入“45324”时,我需要在 long[] 数组中找到该输入的索引并传递char[] 数组的索引,然后输出该位置的值。

所以 45324 索引可能是 12 并且 char[] 数组中的第 12 项可能是 '#' 我尝试了循环但是 pfft 我每次尝试都失败了。我宁愿不必重写代码并将所有这些值再次硬编码到不同类型的数组中。

4

5 回答 5

1
int index = Array.IndexOf(array, long.Parse("45324"));
于 2012-11-14T10:29:17.593 回答
0
for(int i = 0; i < longArray.Length; i++)
{
  if(longArray[i].ToString() == input)
  {
    return i;
  }
}

return -1;
于 2012-11-14T10:29:20.137 回答
0

您可以使用Array.IndexOf来确定数组中某个值的索引。

long numberValue;

// First parse the string value into a long
bool isParsed  = Int64.TryParse(stringValue, out numberValue);

// Check to see that the value was parsed correctly
if(isParsed)
{
    // Find the index of the value
    int index = Array.IndexOf(numberArray, numberValue);

    // Check to see if the value actually even exists in the array
    if(index != -1)
    {
        char c = charArray[index];
        // ...
    }
}
于 2012-11-14T10:42:54.410 回答
0

关于什么:

long input = Int64.Parse("45324");
int index = Array.IndexOf(long_array, input);
char output = default(char);
if(index != -1)
  output = char_array[index];

或者:

long input = Int64.Parse("45324");
int index = -1;
for(int i = 0; i < long_array.Length; i++){
    if(long_array[i] == input){
        index = i;
        break;
    }
}
char output = default(char);
if(index != -1)
   output = char_array[index];
于 2012-11-14T10:44:10.057 回答
0

如果数据没有太大变化,您可以使用Linq将结果转换为字典,从而根据用户输入字符串执行快速查找。

假设你的长数组被调用longs并且你的字符数组被调用chars

var dict=longs
         .Select((x,i)=>new {Key=x.ToString(),Value=chars[i]})
         .ToDictionary(x=>x.Key,x=>x.Value);

现在您可以使用输入字符串进行检查...

例如

if (!dict.ContainsKey(userInput)) // value not in the collection

或者

char value= dict[userInput];
于 2012-11-14T10:56:06.120 回答