9. Strings and Regular Expressions


Strings

A string is basically a sequence of characters.A string is a referencetype. String is immutable.
immutable means a new string object is created every time we alter it
The Strings are used for comparison, append, insert, conversion, copy, format, join, split, trim, remove, replace, and search methods.

        The + operator concatenates strings:
        string s = "C# " + ".NET";
        The [] operator accesses individual characters of a string:
        char c = "welcome"[2];  // c = 'l';
         
         
        Comparison method  ==
        Replace:
        string a = "string";
        // Replace all 't' with 'p'
        string b = a.Replace('t', 'p');
        string str = "Welcome to C# .NET";
        char[] sep = new char[]{' '};
        foreach (string s in str.Split(sep))
                Console.WriteLine(s);
        

String Builder

StringBuilder is mutable. StringBuilder can be changed without copying

        Console.WriteLine("StringBuilder:");
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 10; i++)
        {
            sb.Append(i).Append(" ");
        }
        Console.WriteLine(sb);
        

Regular Expressions

Regular expressions are Patterns used to search or match specified strings in the source code.

Regular expressions are use to create, modify or compare srings.

namespace: System.Text.RegularExpressions

        //Validating EMail:
        public const string EmailPattern =  
        
        public class RegexPatternsClass
        {
            public void TestClient()
            {
                string email = "test@gmail.com";
                bool result = IsEmail(email);
            }
            //Test for Email Validation.
            public  bool IsEmail(string email)
            {
                if (email != null)
                    return Regex.IsMatch(email, EmailPattern) ? true : false;
            }
        }