What are Strings in C#

What are Strings in C#

Arrays of characters is a good example to explain Strings in C#.  But actually Strings are Objects in C#.
While declaring a string variable, an object of type “String”  is  instantiated.
Various useful properties and methods are supported by String objects.

Some examples are given below:
Length –  To get the length of a string.
Insert(index, value) To insert the desired value into the string where the stating / indexing point is specified.  IndexOf(value) to get the first index of the first occurrence of the value within the string.
Remove(index) to remove all characters in the string after the specified index.
Replace(oldValue, newValue) to replace the specified value in any string.
Substring(index, length) to print a substring of the specified length, starting from the given index. If length is not specified, the operation continues to the end of the string.
Contains(value) to return true if the string contains given value.

To understand stings clearly, consider the below given example:

some text
string a = “Hello World”;
Console.WriteLine(a.Length);
//Outputs 11
//Counts Spaces as well

Console.WriteLine(a.IndexOf(‘w’));
//Outputs 6

a = a.Insert(0, “Print This: “);
Console.WriteLine(a);
//Outputs “Print This: Hello World”

a = a.Replace(“This: Hello”, “Wonderful”);
Console.WriteLine(a);
//Outputs “Print Wonderful World”

if(a.Contains(“World”))
Console.WriteLine(“matched”);
//Outputs “matched”

a = a.Remove(9);
Console.WriteLine(a);
//Outputs “Print Won”

Its always better to test and run these codes in a tool like Visual Studio.

Social Share

Leave a Reply

Your email address will not be published. Required fields are marked *