C#
  Home arrow C# arrow Page 7 - Strings and Characters, Part 2
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Strings and Characters, Part 2
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2004-08-03

    Table of Contents:
  • Strings and Characters, Part 2
  • 2.14 Passing a String to a Method that Accepts Only a Byte[ ]
  • 2.15 Converting Strings to Their Equivalent Value Type
  • 2.16 Formatting Data in Strings Problem
  • 2.17 Creating a Delimited String
  • 2.18 Extracting Items from a Delimited String
  • 2.19 Setting the Maximum Number of Characters a String Can Contain
  • 2.20 Iterating Over Each Character in a String
  • 2.21 Improving String Comparison Performance
  • 2.22 Improving StringBuilder Performance
  • 2.23 Pruning Characters from the Head and/or Tail of a String

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Strings and Characters, Part 2 - 2.19 Setting the Maximum Number of Characters a String Can Contain


    (Page 7 of 11 )

    Problem

    You want to ensure that the data entered by a user and assigned to a string does not exceed a certain number of characters.

    Solution

    Use the overloaded constructor of the StringBuilder class, which accepts a maximum capacity. The following code creates a StringBuilder object that has a maximum size of 10 characters:

    System.Text.StringBuilder sbMax = new System.Text.StringBuilder(10, 10);
    sbMax.Append("123456789");
    sbMax.Append("0");

    This code creates a StringBuilder object, sbMax, which has a maximum length of 10 characters. Nine characters are appended to this string and then a tenth character is appended without a problem. However, if the next line of code is executed:

    sbMax.Append("#");

    The length of sbMax goes beyond 10 characters and an ArgumentOutOfRangeException is thrown.

    Discussion

    The string object is immutable and, as such, does not have a built-in method to prevent its length from going beyond a certain point. Fortunately, the StringBuilder object contains an overloaded constructor that allows the maximum size of its string to be set. The StringBuilder constructor that we are concerned with is defined as follows:

    public StringBuilder(int initialCapacity, int maxCapacity)

    For most applications, the initialCapacity and maxCapacity can be identical. This way gives you the best performance, overall. If these two parameters are not identical, it is critical that these two parameters can coexist. Take, for example, the following code:

    System.Text.StringBuilder
    sbMax = new System.Text.StringBuilder(3, 12);
    sbMax.Append("1234567890");
    sbMax.Append("0");
    sbMax.Append("#");

    which will throw an ArgumentOutOfRangeException as the final # character is appended. This configuration incorrectly allows a maximum of only 11 characters instead of the 12 indicated.

    The following line of code:

    System.Text.StringBuilder sbMax = new System.Text.StringBuilder(30, 12);

    also throws an ArgumentOutOfRangeException. This time, the initialCapacity parameter is larger than maxCapacity, causing the exception. While you may not be explicitly writing these values for your application, if you are calculating them using some type of expression, you may run into these problems.

    To handle an attempt to append characters to the StringBuilder string, forcing it beyond the maximum size, wrap any code to append text to the StringBuilder object in a try-catch block:

    try

    {

    sbMax.Append("New String"); } catch(ArgumentOutOfRangeException rangeE)
    {

    // Handle overrun here
    }

    In addition to the Append method, you should also wrap any AppendFormat, Insert, and Replace methods of the StringBuilder object in a try-catch block. Any of these methods can allow characters to be added to the StringBuilder string, potentially causing its length to exceed its maximum specified length.

    See Also

    See the “StringBuilder.Append Method” topic in the MSDN documentation.

    Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

    Visit the O'Reilly Network http://www.oreillynet.com for more online content.

    More C# Articles
    More By O'Reilly Media


       · The encoder no longer accepts byte arrays only ubyte arrays so this information is...
     

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek