Strings in C# with Examples

To store textual data in a variable in C#, we have to use the string type. Strings in C# are combinations of characters. For example:

  • "C# is fun!"
  • "codescracker"
  • "Hey buddy, what's up?"

Please note: Strings are enclosed within a quote.

Here is an example that shows how we can create a string type variable in C#.

string myvar;

To initialize any string value to a string type variable, just quote the string or text and initialize it to the variable in this way.

string myvar = "";

C# String Example

Now let me create an example in C# that demonstrates strings. This example will receive input from the user and print the entered data back on the output console.

Console.WriteLine("Enter anything: ");
string mytext = Console.ReadLine();

Console.WriteLine("You entered: " + mytext);

The snapshot given below shows the sample run of the above C# example after executing it. I took this snapshot after executing this C# code in Microsoft Visual Studio.

c sharp strings example

I used a red line to draw your attention to the output text that is related to the program. I have used "Learning C# is Fun!" as input.

Find Length of String in C#

To find the length of a specified string, use the C# Length property. Here is an example demonstrating the use of the Length property.

Console.WriteLine("Enter the String: ");
string str = Console.ReadLine();

Console.WriteLine("\nLength of the String = " + str.Length);

The sample run with user input "codescracker" should exactly be

c sharp length of string example

Convert Uppercase String to Lowercase in C#

To convert an uppercase string to its lowercase counterpart, use the ToLower() method in this way.

string x = "CODESCRACKER";
string y = "C# Programming is Fun!";


The output should exactly be:

c# programming is fun!

Convert Lowercase String to Uppercase in C#

To convert an lowercase string to its uppercase counterpart, use the ToUpper() method in this way.

string x = "codescracker";
string y = "C# Programming is Fun!";


The output should exactly be:


String Concatenation in C#

String concatenation in C# can be accomplished in this manner by using the Concat() method.

string x = "codescracker";
string y = "C# Programming is Fun!";

Console.WriteLine(string.Concat(x, y));

The output should exactly be:

codescrackerC# Programming is Fun!

You can also use the + operator to perform the string concatenation in this way.

string x = "codescracker";
string y = "C# Programming is Fun!";

Console.WriteLine(x + y);

You will get the same output as the previous example's output.

C# Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube