find and solve || findandsolve.com
Please wait.....

C# Strings

In C#, strings are used as array of characters. However, most common practice is to use the string keyword to declare string variable. The string keyword is an alias for the System.String class.

To create string object we use one of the following methods:

  •  By assigning a string literal to a String variable
  •  By using a String class constructor
  •  By using a string concatenation operator(+)
  •  By retrieving a property or calling a method that returns a string
  •  By calling a formatting method to convert a value or an object to its string representation.


C# String Declaration and Initialization

There are the different ways of declaring and initializing  variables using string keyword.

For some example

// Declare without initializing here.
string str;
// Declaring and also Initializing
string str1 = "Welcome to findandsolve";
String str2 = "Hello World!";
// Initialize an empty string.
string str3 = String.Empty;
// Initialize to null.
String str4 = null;
// Creating a string from char
char[] letters = { 'A', 'B', 'C','D'};
string str5 = new string(letters);

If  we observe the above code as given above snippet, we created string variables using string and String keywords with or without initializing values based on our requirements.




Example to demonstrate this-

   using System;
namespace StringApplication {
       class Program {
            static void Main (string[] args) {
           // from string literal and string concatenation
           string fname, lname;
           fname = “Find”;
            lname = “Solve”;
           char [] letters = { ‘H’ , ‘e’, ‘l’, ‘l’, ‘o’ };
           string [] sarray = { “Hello”, “From” , “Tutorials” , “Point” };
           string fullName = fname + lname;
           Console.WriteLine (“Full Name: {0}” , fullname);
           // by using string constructor { ‘H’, ‘e’ , ‘l’, ‘l’ , ‘o’ };
           string greetings = new string (letters);
           Console.WriteLine (“Greetings: {0}”, greetings);
         // methods returning string { “Hello” , “From”, “Find and” , “Solve” };
         string message = String.Join (“ “, sarray);
         Console.WriteLine (“Message: {0}” , message);
        // formatting method to convert a value
       DateTime waiting = new DateTime ( 2021, 9, 9, 17, 58, 1);
      string chat = String.Format(“Message sent at {0:t} on {0:D}” , waiting);
     Console.WriteLine(“Message: {0}”, chat);
  }
  }
}

When the above code is compiled and executed, it produces following result:

Full Name: Find Solve

Greetings: Hello

Message: Hello From Find and Solve

Message: Message sent at 5:58 PM on Wednesday, September 9, 2021


Properties of the String Class


PropertyDescription

Char Char is use to get the characters from the current string object based on the specified position.
LengthLength always returns the number of characters in the current String object.