Tuesday, 14 October 2014

C# Strings

C# strings
In C#, a string is an object of type string and the value of that string is text.We can use C#
strings as array of characters but more common and preferable practice is to declare a string variable for using strings. C# treats the strings as objects that encapsulate all the manipulation, sorting, and searching methods normally applied to strings of characters. Each string in C# is immutable sequence of Unicode characters. In simple words, we can say that the methods in C# to change or modify the string actually does not change the string but they only return a modified copy of that C# string and the original string remains intact.

Creating a String in C#

In C# strings most common way to create string is to assign quoted strings of characters which is knows as string literal, to a user-defined variable with string type.
string overString =  "This is a string literal";
Our string is between the double quotes. In the same way quoted strings can include escape characters like "/n" or "/t" and i hope you have knowledge of escape characters.
We can also create string objects in more ways from the above one :

  • Using a string class constructor.
  • Using the string concatenation operator(+).
  • Retrieving a property or calling a method that will return a string.
  • Calling any formatting method to convert a value or object to its storing representation.



using System;
namespace StringApp
{
    class Program
    {
        static void Main(string[] args)
        {
           //Through the string literal and string concatenation
            string firstName, lastName;
            firstName = "Paul";
            lastName = "Walker";
            string fullName = firstName + lastName;
            Console.WriteLine("Full Name: {0}", fullName);
            //Using string constructor
            char[] sLetters = { 'H', 'e', 'l', 'l','o' };
            string greetings = new string(sLetters);
            Console.WriteLine("Greetings: {0}", greetings);
            //Methods returning string
            string[] sArray = { "Hello", "From", "Tutorials", "Point" };
            string meSSage = String.Join(" ", sArray);
            Console.WriteLine("Message: {0}", meSSage);
            //Formatting method to convert a value
            DateTime waiting = new DateTime(2014, 10, 10, 17, 58, 1);
            string chat = String.Format("Message sent at {0:t} on {0:D}",
            waiting);
            Console.WriteLine("Message: {0}", chat);
            Console.ReadKey() ;
        }
    }
}

C# strings has various properties and methods for working with string objects and we will work on these further.

No comments:

Post a Comment