Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday, 13 July 2015

STRING SEARCH USING REGEX METHOD IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

REGEX SEARCH IN STRING

REGEX class is used to represent a Regular Expression. REGEX Searching in the string means an act to search a specified string object within the string. 

There are numerous ways of doing this: 
1) IsMatch()
2) Match()

IsMatch() Method

IsMatch() is used to tell whether the specified regular expression finds a match in the given string. It contains various matching options. It returns a boolean value, i.e. "true" if string object is found within string otherwise return "false".

We are explaining you the most used overload of IsMatch() method.

It contain 3 parameters(P):-
(P1) input: The string to search for a match.
(P2) pattern: The regular expression pattern to match.
(P3) options:
Enumeration values that provide options for matching. 

Match() Method

Match() is used to tell whether the first occurrence of the specified regular expression finds a match in the given string. It contains various matching options. It returns an object that contains information about the match.

We are explaining you the most used overload of Match() method. 


It contain 3 parameters(P):-
(P1) input: The string to search for a match.
(P2) pattern: The regular expression pattern to match.
(P3) options:
Enumeration values that provide options for matching.


Let's see all these method quickly by an example.

Example- C# program that uses all the above method.

Practical Implementation

using System;

namespace AspnetSolutions

{
    class SearchUsingRegex
    {
        public static void
Main() 
        {
            string strURL = "Url is imaginationhunt.blogspot which is run by Engineer's.";
          
            //Matching words start with 'i' and ends with 't':
            string pattern = @"\bi\S*t\b*"; // word is
imaginationhunt.blogspot 
            Console.WriteLine("Using IsMatch() Method");
            if (Regex.IsMatch(strURL, pattern, RegexOptions.IgnoreCase))
            {
                Console.WriteLine("Match found");
            }
            else
            {
                Console.WriteLine("Match not found");
            }
            Console.WriteLine();
            Console.WriteLine("----------------");


            Console.WriteLine("Using Match() Method");

            Match match = Regex.Match(strURL, pattern, RegexOptions.IgnoreCase);
            Console.WriteLine("Captured string in object match is ={0}",match.Value);
            if (match.Success)
            {
                Console.WriteLine("Match found");
            }
            else
            {
                Console.WriteLine("Match not found");
            }

        }
    }
}


Output


The expression matches the word "imaginationhunt.blogspot" and giving success message as "Match found" for both the cases.
[Note]: Captured string in object "match" is same as pattern(i.e. 'imaginationhunt.blogspot') string.

Let's interpret the pattern:

Click imaginationhunt.blogspot to see latest Blogs

Pattern: @"\bi\S*t\b*"

Pattern      Description
@            is the verbatim literal
\bi           Matches a word boundary(Ex- word start with char 'i')
\S           Matches any non-white space character
\tb           Matches a word boundary(Ex- word end with char 't')

Read more about Regular expression:
MSDN Regular Expression Language - Quick Reference
MSDN Regular Expression Syntax 

Applications

Regular expressions are the best way to search without writing any comparison code. Yes, it is not an easy task for developers to make a pattern. But, if made then any string identification, searching and validation become so easy, then doing by various lines of code and methods.


Various application with Regular expression to search strings are:1) Email validation
2) Search Email by pattern
3) URL search
4) Address Path
5) Date Validation
and many more...

To read IS STRING MUTABLE OR IMMUTABLE IN .NET? - Click here.


Related Questions:

#newtoprgm try first program

Q-1 How to validate an Email by Regular Expression?
Ans- User Input Code for validating an Email Address.

Practical Implementation

using System;

namespace AspnetSolutions

{
    class SearchUsingRegex
    {
        public static void
Main() 
        {
            //Email Validating

            Console.WriteLine("Enter your Email");
            string Email = Console.ReadLine();
            string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

            if (Regex.IsMatch(Email, EmailPattern, RegexOptions.IgnoreCase))
            {
                Console.WriteLine("Email: {0} is valid.", Email);
            }
            else
            {
                Console.WriteLine("Email: {0} is not valid.", Email);
            }
 
        }
    }
}


Output



Q-2 Which pattern is used to match white space character?
A) \s
B) \w
C) \d
D) \s\S


Ans- Option(A).
Explanation- 
\w is used to match any word character.(ex- "E"),
\s\S is to match non-white space character.(ex-"_", "img_1"),
\d is used to match any decimal charcter.(ex- "9")


Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Wednesday, 8 July 2015

STRING SEARCH IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

SEARCH IN STRING

Searching in the string means an act to search a specified string object within the string. 

There are numerous ways of doing this: 
1) Contains()
2) IndexOf()
3) LastIndexOf()
4) StartsWith()
5) EndsWith()

Contains() method: 

Contains() return a specified string object within the string. This method is present in System.String Class. It returns boolean value, i.e. "true" if string object is found within string otherwise return "false".

IndexOf() method: 

IndexOf() is used to search the position of the specified character from the given string. Its return type is Integer.


LastIndexOf() method:  

LastIndexOf() is used to search the last position of the specified character from the given string. Its return type is Integer. 
StartsWith() method: 

StartsWith() determines whether the start of this string matches the specified string when compared using the specified comparison option. This method is present in System.String Class. It returns boolean value, i.e. "true" if the string object starts with the string to seek otherwise return "false".

EndsWith() method: 

EndsWith() determines whether the end of this string matches the specified string when compared using the specified comparison option. This method is present in System.String Class. It returns boolean value, i.e. "true" if the string object ends with the string to seek otherwise return "false".

Let's see all these method quickly by an example.

Example- C# program that uses all the above method.

Practical Implementation

using System;

namespace AspnetSolutions

{
    class searchString
    {
        public static void
Main() 
        {
           
string str = "A quick brown fox jump over a lazy dog.";

            // Using Contains() method

            bool value = str.Contains("fox");
            Console.WriteLine("fox contain in string? {0}", value);

            // Using IndexOf() method

            int index = str.IndexOf("jump");
            Console.WriteLine("index is {0}", index);

            // Using LastIndexOf() method

            int lastindexof = str.LastIndexOf("o");
            Console.WriteLine("lastindexof is {0}", lastindexof);


            // Using StartsWith() method
            bool startsvalue = str.StartsWith("A quick");
            Console.WriteLine("Starts with {0}", startsvalue);


            // Using EndsWith() method

            bool endsvalue = str.EndsWith("dog.");
            Console.WriteLine("ends with {0}",endsvalue);

        }
    }
}


Click imaginationhunt.blogspot to see latest Blogs

Output



[Note]:

1. Contains() method is case-sensitive. Except Contains() all other four methods (IndexOf(), LastIndexOf(), StartsWith(), EndsWith()) are case-in-sensitive. 
2. Contains(), StartsWith() and EndsWith() method return boolean value, whereas the other two LastIndexOf() and IndexOf() method return integer values.

To read STRING SEARCH USING REGEX METHOD IN C# - Click here.
 
Related Questions:

#newtoprgm try first program

Q-1 Write the code to calculate the age of John from the given string?

string dateOfBirth = "John was born on 25/05/1992 in Vashi. And today 25/05/2015, his age is?";

Ans- The Solution code is-
            
using System;

namespace AspnetSolutions

{
    class searchString
    {
        public static void
Main()
         {
            string dateOfBirth = "John was born on 25/05/1992 in Vashi. And today 25/05/2015, his age is?";

            string year1 = dateOfBirth.Substring(dateOfBirth.IndexOf("1992"), "1992".Length);
            string year2 = dateOfBirth.Substring(dateOfBirth.IndexOf("2015"), "2015".
Length);

            int age = Int32.Parse(year2) - Int32.Parse(year1);

            Console.WriteLine("Age is {0}", age);

        }
    }
}






Q-2 What will be the output of the code? 

using System;

namespace AspnetSolutions

{
    class searchString
    {
        public static void
Main() 
        {
            string websiteName = "www.imaginationhunt.blogspot.com";

            int searchResult = websiteName.LastIndexOf("blogsot");
            Console.WriteLine(searchResult);

        }
    }
}

A) -1
B) 20
C) Exception
Ans- Option(A).
Explanation- If specified string is not found in given string then LastIndexOf() would return -1.


Click imaginationhunt.blogspot to see latest Blogs

Keep learning and sharing...

Tuesday, 7 July 2015

STRING SPLIT IN C#

Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 
To read STRING COMPARISON IN C# PART4 - Click here.

SPLIT STRING

Split string means break or cause to break forcibly a complete string into parts, especially into halves or along some substring. Split() method is present in System.String class. This method breaks the string by specifying a Unicode character array. Its return type is a string array.

Let's understand this by an example.

Example- We have a Url string. Now, what we want to do is we want to separate our string by the means of '.' (dot), that is used in. And want the output in the form of string array. 

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main()
         {
            //Our Url
            string emailstr = "www.imaginationhunt.blogspot.com";

            //Dot(.) by which we want to separate our string
            char[] chardotsplitstring = new char[] { '.' };
          
            //using the split method
            string[] resultdotseprator = emailstr.Split(chardotsplitstring, StringSplitOptions.None);
          
            //Using foreach loop loops over this array and displays each word.
            foreach (string responseemail in resultdotseprator)
            {
                Console.WriteLine(responseemail);
            }

        }
    }
}


Output



As you can see in the output window we get each word separately printed. So, this is how we use Split() method.

We have various overloads of Split() method. Of them two most common overloads are

string[] Split(char[] separator, int count);
string[] Split(char[] separator, StringSplitOptions options);

Parameters Used:

P1: separator- an array of unicode character that separate the substrings of this string

P2: count- The maximum number of substrings to return.

P3: options- StringSplitOptions has two properties
(i) System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements from the array returned.
(ii) StringSplitOptions.None to include empty array elements in the array returned.
Let's use this in a real time example. 

Example- We have a connection string and we want to split our string by ';' separator. 

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main() 
        {
            string connectionString = "Data Source=.;Initial Catalog=dbInsertNameAndDate;Integrated Security=True";

            char[] connectionsemicolonseprator = new char[] { ';' };
            string[] responseconnstring = connectionString.Split(connectionsemicolonseprator, StringSplitOptions.None);

            for (int i = 0; i <= responseconnstring.Length-1; i++)
            {
                Console.WriteLine(responseconnstring[i]);
            }

        }
    }

}
 
Output



Click imaginationhunt.blogspot to see latest Blogs


[Note]: One more important thing to know about Split() is we can separate by one or more characters specified in an array, and then return these substrings in a string array.

Let's see quickly by an example.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main() 
        { 
            string strline = "Line@A, quick, brown fox. jump; over: a lazy% dog.";

             // We are using more than one separtor
             char[] charmoresplitstring = new char[] { '@', ',', ' ', '.', ';', ':', '%' };

            string[] resultmoresplitstring = strline.Split(charmoresplitstring, StringSplitOptions.RemoveEmptyEntries);
            foreach (string response in resultmoresplitstring)
            {
                Console.WriteLine(response);
            }

        }
    }

}

Output  

Hence, with Split() method we separate String. 

To read STRING SEARCH IN C# - Click here.
 

Related Questions:

#newtoprgm try first program

Q-1 In the following piece of code, which part result in error? 

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main()
         { 
            // Path Url
            string dir = @"C:\Users\Documents\Pictures";
            // Split on directory separator.(\)
            string[] directorypartsseparator = dir.Split('\');
            foreach (string part in directorypartsseparator)
            {
                Console.WriteLine(part);
            }

         }
    }

}

A) ('\')
B) '@' symbol
C) using only single parameter in Split() method
D) no problem
Ans- Option(A).
Explanation- using single backslash(\) result in escape sequence error. So you need to take (\\).

Q-2 Method used to remove white space from string?
A) Split()
B) Substring()
C) TrimEnd()
D) Trim()
Ans- Option(D).

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and coding... 

Featured post

Think that makes you rich and richer

 Napolean said: “You can think and grow rich, but if you can be brought up like most people with work and you won't starve, this wil...