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

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...