1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Programming Tutorial - About Strings and Chars

By , About.com Guide

4 of 10

Still More about Strings and Chars in C# Programming

The notation '\udddd' defines a Unicode character. The first 128 characters are the same as ASCII characters so the following works:
char x = '\u0041';
Console.WriteLine("x= {0}",x);
Prints out the character A.

Download example 2


   for (int i = 0; i < s.Length; i++)
   {
     char c = s[ i ];
   }

The string type has a ToCharArray() method that outputs an array of chars. That's not something you'll use a lot but it comes in handy with Trim() (see later). Example two shows mixing Unicode Chars with strings and printing the characters out individually or all at once using the foreach statement. We'll return to foreach as it not only a compact and less buggy way of enumerating through a string or collection, it is essential for classes that implement IEnumerable. Plus foreach also works with char arrays like this.

   char[] chars ={'*','!','^' };
   foreach(char c in chars)
      Console.Write("{0}", c);

Using StringBuilder

When working with strings, you are likely to be doing
  • Reading/Writing Strings from/to Disk
  • Building strings.
  • Comparing Strings
we'll look at building strings first. As mentioned earlier, strings are immutable which means you can't change them. Confusingly you can actually change a string but only by assigning it a new value. You can't do this:
string s="abcdefg";
s[3]='z';
You'll get an error "Property or indexer 'string.this[int]' cannot be assigned to -- it is read only". The way to do this is with Replace() as in
s= s.Replace('d', 'z');
Doing small string operations is inefficient if done often as each time causes a new String to be created. You can get away with one or two Replaces but any more and you should use the StringBuilder class.

On the next page StringBuilder for Efficiently Building Strings

Explore C / C++ / C#
By Category
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Still More about Strings and Chars in C# Programming

©2009 About.com, a part of The New York Times Company.

All rights reserved.