【发布时间】:2013-11-08 17:37:54
【问题描述】:
我必须编写一个使用哈希表的程序,并且键/值由用户输入。在程序中,我必须输出所有键,但是如果任何键以小“a”开头,我必须让它以大“A”开头。我在最后一步遇到了问题。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Hashtable hashtable = new Hashtable();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Vnesete kluc");
string kluc = Console.ReadLine();
Console.WriteLine("Vnesete podatok");
string podatok = Console.ReadLine();
hashtable.Add(kluc, podatok);
}
foreach (string klucevi in hashtable.Keys)
{
if (klucevi[0] == 'a')
{
klucevi[0] = 'A';
}
Console.WriteLine(klucevi);
}
}
}
}
我在将字符串的第一个元素从“a”转换为“A”的行中遇到错误。
【问题讨论】:
-
你遇到了什么错误?
-
错误:无法将索引器“string.this[int]”的属性分配给 -- 它是只读的。
-
那是因为字符串是不可变的。而且你不能像那样改变密钥。
-
备注:请使用类型安全的
new Dictionary<string, string>()而不是new Hashtable()。