December 7, 2013

Formating Console Output, Characters and Strings

Characters and Strings are the most fundamental data types in a language. If you are able to play with them, your programming experience will be smooth and easy. Some of us really find it difficult to cope up with strings and characters, so in this post, we shall try to explore some useful methods of characters and strings.

Taking input and writing output to the Console: This is one of the most important part of a programming language. You want to see output of the program that you have written. In C#, writing output to the console is easy, but it can be difficult if you do not know some of the tricks that we will explore here below.

Let's think of a scenario, where you want to take an integer number as input, and you would like to check if it's a prime or not.
Step 1: We try to take an integer input. In C#, we take input from the console using Console.ReadLine() and it returns a string.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            int num = Int32.Parse(input);
            Console.WriteLine("My input was " + num);
            Console.Read();
        }
    }
}
Our previous knowledge tells us that Console.WriteLine() takes a string as parameter. In this case, we did build our output string by appending the integer at the end. This is not the best way, but it serves our purpose.
Our attention is primarily on line 10. Why Int32? The answer can be found in the previous post. The data type int is actually mapped to a class called System.Int32. So whatever built-in .NET methods we want to access, we have to access it using the base class, which is Int32. The Parse method takes the string as parameter, and returns our desired integer.
Step 2: We now need to know how to build an output string which is efficient. We already have seen a process at line 11. But there is a method called string.Format, which is more easier and neat. It returns a formatted string which we can output to the Console. Here's a modified version of line 11.

string output = string.Format("My input was {0}",num);
Console.WriteLine(output);
But instead of creating another string object, we can directly do that on the Console.WriteLine method.

Console.WriteLine("My input was {0}",num);
If you are familiar with C or C++, you have probably used printf("%d",i). The string.Format works similar to the printf function. You can also output as many variables as you liked. For example-

Console.WriteLine("i = {0}, j = {1}, k = {2}",i,j,k);
This line will print all values of variables i, j, k etc. You get the idea; the numbers inside the curly brace starts at 0 and increments by 1 for each variable we want to output.
Step 3: Since we know how to take input and provide output, we are now safe to write the logic code. Here is the complete code of a not-so-naive approach.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            int num = Int32.Parse(input);
            bool prime = true;

            for (int i = 2; i * i < num; i++)
            {
                if (num % i == 0)
                {
                    prime = false;
                    break;
                }
            }
            if (prime)
                Console.WriteLine("{0} is a prime", num);
            else
                Console.WriteLine("{0} is not a prime",num);

            Console.Read(); //keeps the console alive
        }
    }
}
If you are not familiar with loops, then just concentrate on the other parts of the program, we shall cover loops in future. This program demonstrates how we can format a console output.

Characters: Character data types, or char in C# represents a single Unicode character. That is 16 bits or 2 bytes in width. When we use a char type, we assign a value with a single quote.

char myCh = 'a';
In case of strings, we use double quotes. In JavaScript, you can use either a single quote or double quote for the strings, it doesn't matter. But in C#, it does matter.

You can do some nice tricky things with characters. .NET provides a whole bunch of built-in methods that are really cool. As for example, look at the following code-

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            char myCh = 'a';
            
            Console.WriteLine("Is it Lowercase? {0}",char.IsLower(myCh));
            Console.WriteLine("Is it Uppercase? {0}", char.IsUpper(myCh));
            Console.WriteLine("Is that a digit? {0}", char.IsDigit(myCh));
            
            Console.WriteLine("============");   //separating the outputs

            myCh = '4';
            Console.WriteLine("Is it Lowercase? {0}", char.IsLower(myCh));
            Console.WriteLine("Is it Uppercase? {0}", char.IsUpper(myCh));
            Console.WriteLine("Is that a digit? {0}", char.IsDigit(myCh));

            Console.Read(); //keeps the console alive
        }
    }
}
These are some of the methods that .NET provided. These methods return boolean results, either True or False. There's much more and you can just experiment and play with them. The output screen in my case -

Strings: The string data type represents a series of Unicode characters. In C# you have to put double quotes around to build a string.

string myStr = "Bangladesh is my country.";
Strings can have escape characters. If you are familiar with other languages, you probably have seen \n as a way to print a new line. The following line is perfectly okay with C#.

string myStr = "This is a line. \n This is in a new line";
C# will automatically handle things like \t or \r etc. for you.The following case is interesting. If you want to specify a file location in your program, for example, "C:\A-Folder\A-File.txt" these things are a bit tricky. The backslash is treated as a special character. So if you put this string directly in your program, you probably will hit the wrong output. You have to tell the compiler that please treat them as directory separator character. How do we do that? You have two solutions:

string myDir = @"C:\A-Folder\A-File.txt";
string myDir = "C:\\A-Folder\\A-File.txt";
You can use any one of them. Both works fine. Personally I like number 1. Its neat and easier to understand your actual file location. The @ symbol tells the compiler that "hey don't worry about escape characters, I know what I am doing". In number 2, you are using another backslash to escape the other backslash.
Since string variables are actually objects, you can some pretty interesting things with them. Some of them are covered in this post, the rest will be shown in a future post.

using System;

namespace Spells
{
    class Program
    {
        static void Main(string[] args)
        {
            string myStr = "this is lowercase string";
            Console.WriteLine(myStr.ToUpper());  //converts all the characters to uppercase
            Console.WriteLine(myStr.Length); //the length of the string
            Console.WriteLine(myStr.LastIndexOf('s'));  //the last position of s
            
            Console.Read(); //keeps the console alive
        }
    }
}
Copy and paste this program in your Visual Studio, hit F5 and see what happens.
I hope this post was fun for you. Keep experimenting with these things, I am sure you will love them.

No comments:

Post a Comment