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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...