Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

8.5. Replacing Characters or Words in a String

Problem

You are given a string in which a complex pattern of characters needs to be replaced with a new string.

Solution

Using the Replace instance method on the Regex class allows for easy replacement of text within a string. The following overloaded Replace methods accept a source string that contains characters or words to be replaced, a matchPattern to match the replaceable text in the source parameter, and a replaceStr string to replace the text matched by matchPattern. In addition there are two parameters, count and startPos, to control the number of replacements allowed and where the replacements start from in the source string, respectively:

using System; using System.Text.RegularExpressions; public static string Replace(string source, char matchPattern, string replaceStr) { return (Replace(source, matchPattern.ToString( ), replaceStr, -1, 0)); } public static string Replace(string source, char matchPattern, string replaceStr, int count) { return (Replace(source.ToString( ), matchPattern.ToString( ), replaceStr, count, 0)); } public static string Replace(string source, char matchPattern, string replaceStr, int count, int startPos) { return (Replace(source.ToString( ), matchPattern.ToString( ), replaceStr, count, startPos)); } public static string Replace(string source, string matchPattern, string replaceStr) { return (Replace(source, matchPattern, replaceStr, -1, 0)); } public static string Replace(string source, string matchPattern, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata