String Handling



String Handling:-
·         A string is a collection of characters, enclosed in “ ”(double quotes).
Note:
            C#.net identifies every string as an object of system.string class. So every string can call the string methods.
                     C                                              C#
               Str upr()                                 class string
              Str lwr()                                   {
             Str len()                                         ToUpper();
            Etc……                                          ToLower();
These are independent methods                 Split();    // etc
             in ‘C’                                          }
Ex:-
using System;

namespace StringMethodsDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "hyderabad";
            string str1 = str.ToUpper();
            string str2 = str.ToLower();
            int len = str.Length;
            Console.WriteLine(str1);
            Console.WriteLine(str2);
            Console.WriteLine(len);
            Console.ReadKey();
        }
    }
}

Properties of strings:-
1.      Length:- Gets the no of characters in the string.
2.      Index:- Returns a character in the string at specified index
Note:- Index starts from ‘0’.
Methods of strings:-
1.      ToUpper():- Converts and returns the string in upper case.
2.      ToLower():- Converts and returns the string in lower case.
3.      Substring(int index):- Returns the string starting from a specific character, upto the end.
4.      Substring(int index,int length):- Returns the specified no of characters in the string, starting from a specific character.
Ex:-
                     using System;
                     using System.Collections.Generic;
                     using System.Linq;
                     using System.Text;

                     namespace StringMethodsDemo
                     {
                         class Program
                         {
                             static void Main(string[] args)
                             {
                                 Console.Write("Enter your name ");
                                 string str = Console.ReadLine();

                                 Console.WriteLine(str[3]);
                                 Console.WriteLine(str.Substring(3));
                                 Console.WriteLine(str.Substring(3, 2));

                                 Console.ReadKey();
                             }
                         }
                     }

            Output:-
            Enter your name Hyderabad
            e
            erabad
            er

5.      Contains():-

Ø  It is used to search the given value in the string.
Ø  Syntax:-  stringvariable.contains(valuetosearch);
Ø  This method returns a Boolean value.
Ø  Returns TRUE, is given value is found in the string.
Ø  Returns FALSE, is given value is not found in the string.

6.      IndexOf():-

Ø  It is used to identify the index of the value in the string.
Ø  This method returns the index (as integer) if the value is found in the string.
Ø  Returns -1 if not found.
Ø  Syntax:   stringvariable.IndexOf(value);

7.      StartsWith():-

Ø  It is used to check the beginning of the string.
Ø  Returns true:  if found
Ø  Returns false: if not found
Ø  Syntax:  stringvariable.StartsWith(value);

8.      EndsWith():-

Ø  It is used to check the ending of the string.
Ø  Returns true:  if found
Ø  Returns false: if not found
Ø  Syntax:  stringvariable.EndsWith(value);
Ex:-
Develop a c# console app, to check the email whether it is correct or not, by using the above string methods.
1.      emails should not have spaces.
            abc xyz@gmail.com
2.      emails ends with .com or .co.in
            abc@gmail.com
            abc@gmail.co.in
3.      @ symbol should be in the middle
Program:-
using System;

namespace StringMethodsDemo2
{
    class Program
    {
        static void Main(string[] args)
        {
            //declare variable
            string Email;

            //read email from console
            Console.Write("Enter email: ");
            Email = Console.ReadLine();

            //email validation
            bool spaces = Email.Contains(" ");
            bool dotcom = Email.EndsWith(".com");
            bool dotcoin = Email.EndsWith(".co.in");
            int atsymbol = Email.IndexOf("@");

            //check
            if (spaces == false && (dotcom == true || dotcoin == true) && (atsymbol > 0 && atsymbol < Email.Length - 1))
            {
                Console.Write("Valid");
            }
            else
            {
                Console.WriteLine("Invalid");
            }

            Console.ReadKey();
        }

        //press f5 to run
    }
}
9.      Replace():-

Ø  It  is used to replace (substitute) each occurace of old char with a new char.
Ø  Syntax:   stringvariable.Replace("old char", "new char");

10.  Split():-

Ø  It  is used to split the string as a string array based on a seperator char.
Ø  Syntax:  stringvariable.Split('seperator');
Ex:-
Demo app on Replace() and Split()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringMethodsDemo3
{
    class Program
    {
        static void Main(string[] args)
        {
            //declare variable
            string str;

            //read value from console
            Console.Write("Enter your string: ");
            str = Console.ReadLine();

            //replace
            string str2 = str.Replace("a", "z");

            //split
            string[] str3 = str.Split(' ');

            //show output
            Console.WriteLine("\nString after Replace: " + str2);

            Console.WriteLine("\nString after split:");
            for (int i = 0; i < str3.Length; i++)
            {
                Console.WriteLine(str3[i]);
            }

            Console.ReadKey();
        }
    }
}

11.  Format():-

Ø  It is used to substitute values in the place holders.
Ø  Syntax:   string.Format("your string here",  values here);
Ø  Place holder:   {0}  {1}  {2}  etc.
Ø  Rule: the no. of place holders & values must be same.

Ex:-
Demo app on string.Format()
___________ has ________ roads.
User 1:   Hyderabad has bad roads.
User 2:   Bangalore has good roads.
{0} has {1} roads.
using System;

namespace StringMethodsDemo4
{
    class Program
    {
        static void Main(string[] args)
        {
            //declare variable
            string str = "{0} has {1} roads";
            string val1, val2;

            //read values from console
            Console.Write("Enter value1: ");
            val1 = Console.ReadLine();
            Console.Write("Enter value2: ");
            val2 = Console.ReadLine();

            //substitute
            string resultstr = string.Format(str, val1, val2);

            Console.WriteLine("result after substitution: " + resultstr);
            Console.ReadKey();
        }
    }
}

No comments:

Post a Comment