Strings in C#



This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

A string in C# is simply a set of 16-bit bytes arranged in sequential memory locations. In other words, a string is simply an array of Unicode characters. C# includes a variety of standard functions to recognize this data organization as a string and emulate the actions provided by operators on true string types in other languages. C# prevents functions from writing outside the bounds of the string's memory area. Listing 20.18 is a Console application that shows some basic manipulation of strings. The program prompts the user for a string, a character to be found, and a character to replace the found characters. The program illustrates simple string initialization, assignment, concatenation and indexing. 

Listing 20.18: Replacing characters in a string

// a string is an array of characters

class TheReplacer
{
    static string s1, s2;
    static char c2, c3;

    public static void Main()
    {

        try
        {
            System.Console.Write("Please enter a string:");
            s1 = System.Console.ReadLine();
            System.Console.Write("Please enter a character to be found:");
            string temp = System.Console.ReadLine();
            c2 = temp[0];
            System.Console.Write("Please enter a character to replace the found chars:");
            temp = System.Console.ReadLine();
            c3 = temp[0];
        }

        finally
        {
        }

        try
        {

            for (int i = 0; i < s1.Length; i++)
            {
                if (c2 == s1[i])
                {
                    s2 += c3;
                }
                else
                {
                    s2 += s1[i];
                }
            }
        }

        finally
        {
            System.Console.WriteLine("\nNew string:" + s2);
            System.Console.ReadLine();
        }
    }
}

The program in Listing 20.18, has this output: 

string.gif

Conclusion

Hope this article would have helped you in understanding Strings in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.