Strings in C#

Simply put, string in C# is nothing but a sequence of characters. Strings are extremely useful. They can be used to store name of persons, place or any other string type value. There are multiple ways for creating string in C#, they have been explained in the following example.

´╗┐using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {

            // string using string literals
            string first_name = "john";
            string last_name = "arryn";

            //string creation using concatenation
            string fullname = first_name + " " + last_name;
            Console.WriteLine(fullname);

            //string creation via character array
            char [] chararray = { 'a', 'b', 'c', 'd', 'e' };
            string str = new string(chararray);
            Console.WriteLine(str);

            // String creation by joining string arrays
            string[] strarray = { "this", "is", "string", "array" };
            string joinedarray = string.Join(",", strarray);
            Console.WriteLine(joinedarray);
            Console.ReadKey();
        }
    }
}

Download the code

The most simplest method of creating a string is by storing a string literal in it. In the above code the string variable first_name contains a string literal “john”. A string can also be created by concatenating two strings via “+” operator.

Strings can also be created by passing character type array to the constructor of the string class. In the above example, character type array named “chararray” is used to create string array “str”. Finally, strings can also be created by using “join” extension method of string class. This method takes two parameters. The first one is the string that you want to append after each string item in the array and the second parameter is the string to join.

String Functions

There is a huge number of functions that can be used to manipulate strings. Some of these functions have been explained in the following example.

´╗┐using System;
namespace CSharpTutorials {

    class Tutorial {
        static void Main(string[] args) {

            string car = "FoRd";

            // convert all  to upper case
            car = car.ToUpper();
            Console.WriteLine(car);

            //convert all to lower case
            car = car.ToLower();
            Console.WriteLine(car);

            //finding length of the string
            int len = car.Length;
            Console.WriteLine(len);

            // Inserting string within a string.
            car = car.Insert(1, "abcd");
            Console.WriteLine(car);

            Console.ReadKey();
        }
    }
}

Download the code

<<< Nullable Types in C#C# Decision statements >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .