Best Way To Use Strings In C#

3 mins read

In C# strings are used for storing text. A string  variable contains a collection of characters surrounded by double quotes.

Code sample

Let us create a variable of type string  and assign it a value:

What Is String Length?

A string in C# is an object, which contain properties and methods that can perform certain operations on strings. For instance, the length of a string can be found with the Length  property.

Code sample:

Other String Methods

String have many methods available, for example the ToUpper()  and ToLower() method, which returns a string converted to uppercase or lowercase.

Code sample:

How to concatenate string

To concatenate string, we can use the +  operator between strings to combine them. It is called concatenation in C#.

Here is a code sample of to use the +  operator to concatenate strings:

In the code above, you will notice that we add some space after "John"  to create a space between firstName  and lastName  on print.

You can also use the string.Concat()  method to concatenate two strings.

Code sample:

What is string interpolation?

String Interpolation is another option of string concatenation, which substitutes values of variables into placeholders in a string. You don’t need to worry about spaces, like with concatenation.

Code sample:

Note: Always use the $  sign when using the string interpolation method.

How can I access strings

You can access the characters in a string by referring to its index number inside square brackets [].

Code sample

In the code sample below, we print the first character in myString :

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

 

Let us give another example that will output “e” which is the second character:

Note: You can also find the index position of a specific character in a string, by using the IndexOf()  method.

Code sample:

The code above will output 1.

Another useful method is Substring() method, which extracts the characters from a string, starting from the specified character position or index, and returns a new string. This method is commonly used together with IndexOf()  to get the specific character position.

Code sample:

Thanks for reading…

Happy Coding!

Leave a Reply

Your email address will not be published.