National library capitalization programming exercise

National library capitalization programming exercise.

The national library is missing a lot of capital. And several lots of capital letters. And also they have a lot of librarians. So they made (by hand) a huge database of all the wrong capital letters in all the books. And now, in exchange for a free library pass, for all the free libraries, they want you to make a function for them:

Given a string and an array of integers representing indexes, capitalize all letters at the given indexes.

For example:
Capitalize("abcdef",[1,2,5]) = "aBCdeF"
Capitalize("abcdef",[1,2,5,100]) = "aBCdeF". //There is no index 100.

For the solution of this coding problem – scroll down.

1) In C# we can read specific index in a string but we cannot edit them. But we can do that in a char array so lets declare one using ToCharArray() function that all string objects have.
2) Now lets go through each item in the array with the indexes, and if the index is inside the length of our string, we will make the character with that index, in our char array, uppercased.

But since I am lazy, and don’t want to make my own methods, I am going to use the one Microsoft made, when they ware making the char class. You know how to make classes and objects right? Well it’s the same. When the language was first created, they added many methods and properties for the different objects. Also they made classes with many methods that we can use. That is what this using keyword in the beginning is. To include them. In Visual Studio, you can see all the methods in let say the char class by typing char. (that is char and a dot) That was what I did 🙂 I don’t remember all the functions but I know that there are some useful classes.


3) So lets use char.ToUpper() to make the characters in the proper indexes uppercase.
4) And then return the result in form of a string.

    public static string Capitalize(string s, List<int> idxs)
    {
        //Step 1
        char[] r = s.ToCharArray(); 
        //Step 2         
        foreach (var item in idxs)
        {
            if ((item < s.Length))
            {
                //Step 3
                r[item] = char.ToUpper(r[item]);                   
            }
        }           
        return new string(r);
    }

And this is an example of toUpper function:

    public static char toUpper(char c)
    {
            if (c >= 'a' && c <= 'z')
            {
                c -= (char)32;
            }
        return c;
    }  

Since the characters have numeric value in the ASCII table, we can do math with them. Try to do similar function but toLower().