Skip to main content

String in C# Explained

String in C#

String is a keyword that is use to represent a sequential collection of characters that is called a text and the string is an object of System.String type.

 We use string keyword to create string variables to hold the particular text which is a sequential collection of characters.

 The string variables can hold any kind of text and by using Length property we can know the number of characters the string variable is holding.

 

Declaration and Initialization of string variable in C#

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

 

     // Declare without initializing.

            string str1;

            // Declaring and Initializing

            string str2 = "Welcome to the world of Csharp Naija";

            String str3 = "Hello World!";

            // Initialize an empty string.

            string str4 = String.Empty;

            // Initialize to null.

            String str5 = null;

            // Creating a string from char

            char[] letters = { 'a', 'b', 'c' };

            string str6 = new string(letters);

 

If we take a closer look at the above code snippet, we will found out that we created a string variables using string and String keywords with or without initializing a values.

Differences between string vs String in C#

From the above string declarations code snippets, we used two keywords called string and String to declare string variables. In C#, the string keyword is just an alias for String so both string and String are equivalent, and you can use whichever the naming convention you prefer to define string variables.

 

String Immutability

 

In C#, string is immutable, that is, the string object cannot be modified once it is created. If any changes made to the string object like add or modify an existing value, then it will simply discard the old instance in memory and create a new instance to hold the new value.

 

For example, when we create a new string variable “message” with text “Welcome”, then a new instance will be created on heap memory to hold this value. Now, if we make any changes to message variable like changing the text from “welcome” to “welcome to Csharp naija”, then the old instance on heap memory will be discarded and another instance will be created on heap memory to hold the variable value instead of modifying the old instance in the memory.

 

If we perform modifications like inserting, concatenating, removing or replacing a value of existing string multiple times, then every time the new instance will be created on heap memory to hold the new value thereby affecting the performance of the application automatically.

 

String Literals (Regular/Verbatim) in C#

 

String literal is a sequence of characters that are enclosed in double quotation marks (" "). We have two kind of string literals available in C#, these are regular and verbatim. The regular literals are useful when we want to embed escape characters like \n, \t, \', \", etc. in C#.

 

String Literals (Regular)

 

Following is an example of using regular string literals to embed escape characters in C#.

 

        string names = "Musa\nSule\nGadabs";

            Console.WriteLine(names);

            /*

            Output:

            Musa

            Sule

            Gadabs

            */

 

            string msg = "Welcome to \"Csharpnaija\" world";

            Console.WriteLine(msg);

            // Output: Welcome to "Csharpnaija" world

 

String Literals (Verbatim)

 

The special character @ will serve as verbatim literal and it is use to represent a multiline string or a string with backslash characters, for example to represent file paths.

 

Following is an example of using verbatim literal @ in C# to represent a multiline string and a file path.

 

               string path = @"C:\Users\Csharp naija\Documents\";

            Console.WriteLine(path);

 

            //Output: C:\Users\Csharp naija\Documents\

 

            string msg = @"Hi Guys,

                Welcome to Csharp naija World

                Learning Made Easy";

            Console.WriteLine(msg);

 

            /* Output:

            Hi Guest,

                        Welcome to Csharp naija World

                        Learning Made Easy

            */

 

            string msg1 = @"My wife's name is ""Sakinat.""";

            Console.WriteLine(msg1);

             //Output: My wife's name is "Sakinat."

 

Format Strings in C#

 

The format string is a string whose contents can be determined dynamically at runtime. We can create a format string by using the Format method and embedding placeholders in braces that will be replaced by other values at runtime.

 

Following is the example of using a format string to determine the string content dynamically at runtime.

 

        string name = "Musa Sule";

            string location = "Abuja, Nigeria";

            string user = string.Format($"Name: {name}, Location:                {location}");

            Console.WriteLine(user);

 

            // Output: Name: Musa Sule, Location: Abuja, Nigeria

 

C# Access Individual Characters from Strings

 

We can access individual characters of a string by using array notation with index values as shown in the example below.

 

        string name = "Musa Sule Gadabs";

            for (int i = 0; i < name.Length; i++)

            {

                Console.Write(name[i]);

            }

 

            // Output: Musa Sule Gadabs

 

C# String Properties

 

The following table lists the available string properties in C#.

 

Property

Description

Chars

It helps us to get the characters from the current string object based on the specified position.

Length

It returns the number of characters in the current String object.

 

C# String Methods

The string class contains various methods to manipulate string objects.

The following table lists important string methods available in C# programming language.

Method

Description

Clone()

It returns a reference to this instance of String.

Compare(String, String)

It compares two specified String objects and returns an integer that indicates their relative position in the sort order.  

Concat(String, String)

It concatenates two specified instances of String.

Contains(String)

It returns a value indicating whether a specified substring occurs within this string.

Copy(String)

It creates a new instance of String with the same value as a specified String.

Format(String, Object)

It replaces one or more format items in a specified string with the string representation of a specified object

Trim()

It removes all leading and trailing white-space characters from the current String object.

ToLower()

It converts a given string to lowercase.

ToUpper()

It converts a given string to uppercase.

Split(Char[])

It splits a string into substrings that are based on the characters in an array.

Substring(Int32)

It retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

IndexOf(String, Int32, Int32)

Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions.

 

This is how we can use strings in our applications to hold the required text in C#.

 

Thank you

 

References

1.     Tutlane

2.     MicrosoftDocumentation


Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...