ideas | discover | explore

Tuesday, January 15, 2013

C# 19 – String manipulation – Stuff you could do with C# strings


---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


Welcome to another tutorial from verycsharpedge!

I this tutorial we will learn about the different stuff you could do with C# strings.

We will look into the following methods/properties:

·         Contains()
·         EndsWith()
·         Equals()
·         IndexOf()
·         Insert()
·         Length
·         PadLeft()
·         PadRight()
·         Remove()
·         Replace()
·         Split()
·         StartsWith()
·         Substring()
·         ToLower()
·         ToUpper()
·         Trim()
·         TrimEnd()
·         TrimStart()

OK, Let’s Begin!

1.       Create a new console project.
2.       Add this line of code inside of main.

string myString = "Hello world!";
Console.WriteLine("myString = Hello world!");

Console.ReadLine();

This line of code creates a variable ‘myString’ with data type of string. Next it outputs  to console showing what variable where going to work in the next steps. Console.Readline() allows us to see the output before exiting the program.

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


3.       Before the line Console.Readline() add this code.

Console.WriteLine("- Using the Contains() method -");
if (myString.Contains("Hello"))
Console.WriteLine("Your string does contain Hello");
Console.WriteLine();

Focus on the [if] statement. This line shows us how to us the Contains() method. The method returns true if the variable has the parameters passed which is ‘Hello’ otherwise it returns false.

4.       Before the line Console.Readline() add this code.

Console.WriteLine("- Using the EndsWith() method -");
if (myString.EndsWith("world!"))
Console.WriteLine("Your string does end with 'world!'");
Console.WriteLine();

This section of code shows the method EndsWith() which is like Contains() but only checks at the end of the string.

5.       Before the line Console.Readline() add this code.

Console.WriteLine("- Using the Equals() method -");
if (myString.Equals("Hello world!"))
Console.WriteLine("Yes it's equal to 'Hello world!'");
Console.WriteLine();

This section of code show the method Equals which compares the passed string parameter to the string variable. It returns true if it matches otherwise it returns false.

6.       Before the line Console.Readline() add this code.

Console.WriteLine("- Using the IndexOf() method -");
Console.WriteLine("The index of 'w' is " + myString.IndexOf('w'));
Console.WriteLine();

The IndexOf() method returns the position of the parameter being passed. The index starts with zero.

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


7.       Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Insert() method -");
Console.WriteLine(myString.Insert(0, "Another "));
Console.WriteLine();

The Insert() method inserts a string on the desired index.

8.       Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Length property -");
Console.WriteLine("The length of 'Hello world!' is " + myString.Length);
Console.WriteLine();

The Length property returns the number of characters in a string.

9.       Before the line Console.Readline() add this code.

Console.WriteLine(" - Using PadLeft() method -");
Console.WriteLine(myString.PadLeft(20));
Console.WriteLine();

This section of code shows PadLeft() method in action. It adds spaces to the left of the string. It also has the option to specify the character to use for pad.

10.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using PadRight() method -");
Console.WriteLine(myString.PadRight(20,'#'));
Console.WriteLine();

This section of code show PadRight() which is the opposite of PadLeft(). You can also specify a padding character as a second parameter.

11.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Remove() method -");
Console.WriteLine("Remove all the character starting at index 6");
Console.WriteLine(myString.Remove(6));
Console.WriteLine();


The Remove() method removes a certain sequence of characters specified on the passed parameter as the starting index. It also has the option to remove a specific number of characters as a second parameter.

12.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Replace() method -");
Console.WriteLine("Replace the word 'world' in the string 'Hello world!' with 'Mars'");
Console.WriteLine(myString.Replace("world", "Mars"));
Console.WriteLine();

This section shows the use of the Replace() method. This method replaces the string specified in the first parameter with the string specified in the second parameter.

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


13.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Split property -");
string[] words = myString.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.WriteLine();

The method Split() turn the string into an array of strings that are separated by a specified character which is a space in this example.

14.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using StartsWith() method -");
Console.WriteLine("'Hello world!' starts with 'Hello' is " + myString.StartsWith("Hello"));
Console.WriteLine();

The method StartsWith() checks if the string begins with the string that is passed as the first parameter. It returns true if it matches and returns false if not.

15.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Substring() method -");
Console.WriteLine(myString.Substring(0, 5));
Console.WriteLine();

The Substring() method extracts a sequence of characters that starts from the specified index(first parameter) together with the number of characters(second parameter) and returns a string. There is also an option to pass just the starting index which extracts characters up until the end of the string.

16.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using ToLower() method -");
Console.WriteLine(myString.ToLower());
Console.WriteLine();

This sections shows ToLower() method which returns a string turned into lowercase letters.

17.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using ToUpper method -");
Console.WriteLine(myString.ToUpper());
Console.WriteLine();

This sections shows ToUpper() method which returns a string turned into uppercase letters.

18.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using Trim() method -");
myString = "          Hello world!           ";
Console.WriteLine(myString.Trim());
Console.WriteLine();

The Trim() method removes trailing and leading spaces of the string.

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


19.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using TrimEnd() method -");
Console.WriteLine(myString.TrimEnd());
Console.WriteLine();

The TrimEnd() method removes  trailing spaces from the string.

20.   Before the line Console.Readline() add this code.

Console.WriteLine(" - Using TrimStart() method -");
Console.WriteLine(myString.TrimStart());
Console.WriteLine();

The TrimStart() method removes leading spaces from the string.

21.   After all the code run the application by pressing F5. Your output should look similar to the following image.




Hope you enjoyed our long tutorial.

Be happy and keep coding!

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


Saturday, January 12, 2013

C# 18 – String Manipulation – Creating a Palindrome Checker


---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


In this tutorial we will be doing some string manipulation by creating a program called Palindrome Checker that will determine if a word or a string of letters is a palindrome.

Before we proceed we need to know what is the meaning of a palindrome.

What is a palindrome? According to Wikipedia:
“A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers.”

Which means a word is read the same whether it’s in normal order or in reversed order.
e.g. 
kayak
nissin
madam

Ok let’s begin.

1.     Create a new console project.
2.     Add the following code inside of class Program.

static void Main(string[] args)
       {
            string input;

            Console.WriteLine("Welcome to Palindrome Checker");
            Console.WriteLine("- The software will check if your input is a palindrome. -");
            Console.WriteLine("");
            Console.Write("Enter a string: ");
            input = Console.ReadLine();

            if (IsPalindrome(input))           
                Console.WriteLine(input + " is a palindrome.");
            else
                Console.WriteLine(input + " is a not palindrome.");

            Console.WriteLine("");
            Console.WriteLine("Press any key to exit.");

            Console.ReadLine();
        }

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------


        private static bool IsPalindrome(string input)
        {
            string reverse = "";

            for (int i = input.Length-1; i >= 0; i--)
            {
                reverse = reverse + input[i];
            }
           

            if (input.Equals(reverse))
                return true;

            return false;
        }

3.     Press F5 to run the program. You output should be something similar below.


You have noticed in the output above that I entered the word “kayak” and pressed Enter. After that the result is shown which is “kayak is a palindrome” in this example.

What we will try to focus our attention now is for this function.

private static bool IsPalindrome(string input)
{
string reverse = "";

       for (int i = input.Length-1; i >= 0; i--)
       {
              reverse = reverse + input[i];
       }
            
       if (input.Equals(reverse))
              return true;

return false;
}

This is the main function that checks if a given string is a palindrome. It creates a variable ‘reverse’ that will hold the reversed string. It enters a loop which starts at the end of the string and then moves backwards one character at a time and stores that character to the ‘reverse’ variable.

After the reversal is complete the next step is to check whether the ‘input’ string is indeed equal to the ‘reverse’ string. If they are equal then the function should return true or false if its not.

Hope you enjoyed our simple and quick tutorial.

Be happy and keep coding!

---------------------------------------------------------------------------------------------------------------------------
Manage and share your stuff!
or
---------------------------------------------------------------------------------------------------------------------------