2

Changing a string element in hashtable to C #

 3 years ago
source link: https://www.codesd.com/item/changing-a-string-element-in-hashtable-to-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Changing a string element in hashtable to C #

advertisements

I have to write a program which use hashtable and the keys/values are input by the user. In the program, I have to output all the keys, however if any key starts with small 'a', I have to make it start with a big 'A'. I have a problem in the last step.

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);
            }

        }
    }
}

I'm getting an error on the line where I'm converting the first element of the string if it's 'a' to 'A'.


You can't dynamically change keys. Most simple approach is check the key before you add to the collection:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Vnesete kluc");
    string kluc = Console.ReadLine();
    if (kluc.StartsWith("a"))
        kluc = "A" + kluc.Substring(1);
    Console.WriteLine("Vnesete podatok");
    string podatok = Console.ReadLine();
    hashtable.Add(kluc, podatok);
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK