Convert a character to the string in C#

C# changing over a character to string: Here, we will figure out how to change over a character to the string in C#?

Given a character and we need to change over it into a string in C#.

Changing over char to string

To change over a character to the string, we use ToString() strategy, we call technique with the character and it returns string changing over Unicode character to the string.

Example:

    Input:
    char chr = 'X';
    
    Function call:
    string str = chr.ToString();

    Output:
    str: "X"

C# Example to change over a character to the string:

In this example, we have a character and changing over it into the string, and furthermore we have a string and convert all characters to the string in the strings and printing the sorts and values.

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            //character variable
            char chr = 'X';

            //converting char to string
            string str = chr.ToString();

            //printing types and values
            Console.WriteLine("Type of chr: " + chr.GetType());
            Console.WriteLine("Type of str: " + str.GetType());

            Console.WriteLine("chr: " + chr);
            Console.WriteLine("str: " + str);
            
            //converting each characters of string into string[]
            string str1 = "Hello world!";
            string temp_str ="";
            foreach (char item in str1)
            {
                Console.WriteLine("value: {0}, Type: {1}", item, item.GetType());
                temp_str = item.ToString();
                //converting and print char as string
                Console.WriteLine("value: {0}, Type: {1}", temp_str, temp_str.GetType());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

Type of chr: System.Char
Type of str: System.String
chr: X
str: X
value: H, Type: System.Char
value: H, Type: System.String
value: e, Type: System.Char
value: e, Type: System.String
value: l, Type: System.Char
value: l, Type: System.String
value: l, Type: System.Char
value: l, Type: System.String
value: o, Type: System.Char
value: o, Type: System.String
value:  , Type: System.Char
value:  , Type: System.String
value: w, Type: System.Char
value: w, Type: System.String
value: o, Type: System.Char
value: o, Type: System.String
value: r, Type: System.Char
value: r, Type: System.String
value: l, Type: System.Char
value: l, Type: System.String
value: d, Type: System.Char
value: d, Type: System.String
value: !, Type: System.Char
value: !, Type: System.String

Leave a Comment

error: Alert: Content is protected!!