C#
  Home arrow C# arrow Page 10 - Strings and Characters, Part 1
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  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
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 1
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 17
    2004-07-21

    Table of Contents:
  • Strings and Characters, Part 1
  • 2.2 Determine if a character is in a Specified Range
  • 2.3 Controlling Case Sensitivity when Comparing Two Characters
  • 2.4 Finding All Occurrences of a Character Within a String
  • 2.5 Finding the Location of All Occurrences of a String Within Another String
  • 2.6 The Poor Man’s Tokenizer Problem
  • 2.7 Controlling Case Sensitivity when Comparing Two Strings
  • 2.8 Comparing a String to the Beginning or End of a Second String
  • 2.9 Inserting Text into a String
  • 2.10 Removing or Replacing Characters Within a String
  • 2.11 Encoding Binary Data as Base64
  • 2.12 Decoding a Base64-Encoded Binary

  • 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 1 - 2.10 Removing or Replacing Characters Within a String


    (Page 10 of 12 )

    Problem

    You have some text within a string that needs to be either removed or replaced with a different character or string. Since the replacing operation is somewhat simple, you do not require the overhead of using a regular expression to aid in the replacing operation.

    Solution

    To remove a substring from a string, use the Remove instance method on the string class. For example:

    string name = "Doe, John";
    name = name.Remove(3, 1);
    Console.WriteLine(name);

    This code creates a new string and then sets the name variable to refer to it. The string contained in name now looks like this:

    Doe John

    If performance is critical, and particularly if the string removal operation occurs in a loop so that the operation is performed multiple times, you can instead use the Remove method of the StringBuilder object. The following code modifies the str variable so that its value becomes 12345678:

    StringBuilder str = new StringBuilder("1234abc5678", 12);
    str.Remove(4, 3);
    Console.WriteLine(str);

    To replace a delimiting character within a string, use the following code:

    string commaDelimitedString = "100,200,300,400,500"; commaDelimitedString = commaDelimitedString.Replace(',', ':'); Console.WriteLine(commaDelimitedString);

    This code creates a new string and then makes the commaDelimitedString variable refer to it. The string in commaDelimitedString now looks like this:

    100:200:300:400:500

    To replace a place-holding string within a string, use the following code:

    string theName = "Mary";
    string theObject = "car";
    string ID = "This is the property of .";
    ID = ID.Replace(" ", theObject);
    ID = ID.Replace(" ", theName);
    Console.WriteLine(ID);

    This code creates a new string and then makes the ID variable refer to it. The string in ID now looks like this:

    This car is the property of Mary.

    As when removing a portion of a string, you may, for performance reasons, choose to use the Replace method of the StringBuilder class instead. For example:

    string newName = "John Doe";

    str = new StringBuilder("name = ");
    str.Replace(" ", newName);
    Console.WriteLine(str.ToString());

    str.Replace('=', ':');
    Console.WriteLine(str.ToString());

    str = new StringBuilder("name1 = , name2 = ");
    str.Replace(" ", newName, 7, 12);
    Console.WriteLine(str.ToString());
    str.Replace('=', ':', 0, 7);
    Console.WriteLine(str.ToString());

    This code produces the following results:

    name = John Doe
    name : John Doe
    name1 = John Doe, name2 = <FIRSTNAME>
    name1 : John Doe, name2 = <FIRSTNAME>

    Note that when using the StringBuilder class, you must use the System.Text namespace.

    Discussion

    The string class provides two methods that allow easy removal and modification of characters in a string: the Remove instance method and the Replace instance method. The Remove method deletes a specified number of characters starting at a given location within a string. This method returns a new string object containing the modified string.

    The Replace instance method that the string class provides is very useful for removing characters from a string and replacing them with a new character or string. At any point where the Replace method finds an instance of the string passed in as the first parameter, it will replace it with the string passed in as the second parameter. The Replace method is case-sensitive and returns a new string object containing the modified string. If the string being searched for cannot be found in the original string, the method returns a copy of the original string object.

    The Replace and Remove methods on a string object always create a new string object that contains the modified text. If this action hurts performance, consider using the Replace and Remove methods on the StringBuilder class.

    The Remove method of the StringBuilder class is not overloaded and is straightfoward to use. Simply give it a starting position and the number of characters to remove. This method returns a reference to the same instance of the StringBuilder object whose Replace method modified the string value.

    The Replace method of the StringBuilder class allows for fast character or string replacement to be performed on the original StringBuilder object. These methods return a reference to the same instance of the StringBuilder object whose Replace method was called.

    Note that this method is case-sensitive.

    See Also

    See the “String.Replace Method,” “String.Remove Method,” “StringBuilder.Replace Method,” and “StringBuilder.Remove Method” topics 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


     

    C# ARTICLES

    - 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#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT