Best way for this string.replace?

Posted on 2004-08-20
Last Modified: 2010-04-15
hoi all...
i have a string with some placeholders in it. this string is added to a StringBuilder in a loop. While adding it, i replace each placeholder with another stirng. currently it looks like this:
.... loop start...
    "[forumSubject]", forumSubject).Replace(
    stringPlaceholderOne, oneTopic.getReplyCount().ToString()).Replace(
    "[countViews]", oneTopic.getViewCount().ToString()).Replace(
    "[lastPostAuthor]", oneTopic.getLastPostAuthorNick()).Replace(
    "[lastPostDate]", oneTopic.getLastPostDateFormatted())
... loop end...

the code above has a problem:
If a placeholder variable ("stringPlaceholderOne") is an empty string (length=0), then the .Replace() throws an exception.

What is the best way to handle this?
I thought about a simple code like this:
static public string replaceInString(string inString, string inFind, string inReplaceWith) {
   if (inString.IndexOf(inFind) >= 0) {
      return inString.Replace(inFind, inReplaceWith);
   } else {
      return inString;

But I believe there are better ways to do it... e.g. extend the normal string with my own replace method?
is this possible? how?
any other idea?

Thank you
Question by:Smoerble
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
LVL 10

Expert Comment

ID: 11857507
Why would "stringPlaceholderOne" be null?
LVL 10

Expert Comment

ID: 11857508
Or, sorry: An empty string?
LVL 10

Expert Comment

ID: 11857742
Oh - my apologies again!  I understand the problem now...  Unfortunately you cannot extend (inherit from) the System.String or System.Text.StringBuilder classes, as they are sealed.
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.


Author Comment

ID: 11858141
Hi again.
For clarification:
There might be the following case:
stringPlaceholderOne = "";

In this case, teh string.Replace() crashes.

So, if you say, I can't extend the string class... any idea, what else I could do to get it really fast done?
LVL 14

Assisted Solution

AvonWyss earned 500 total points
ID: 11858174
Well, it does make sense that you cannot use "" as search pattern for replacements.

Try this: before the call, make sure that stringPlaceholderOne is not empty. I'd suggest this workaround:

if (stringPlaceholderOne.Length==0)

Then it will work as expected, since the placeHolderOne will not be ampty, but will contain a pattern which will certainly not appear in the string to be replaced.
LVL 14

Accepted Solution

AvonWyss earned 500 total points
ID: 11858189
Also, it may be worth checking your code for a more efficient solution like this, which can handle any placeholder in square brackets:

uses System.Text.RegularExpressions;

      private string ReplacePlaceholder(Match match) {
            switch (match.Groups["placeholder"].Value) {
            case "forumSubject":
                  return forumSubject;
            case "countViews":
                  return oneTopic.getViewCount().ToString();
            case "lastPostAuthor":
                  return oneTopic.getLastPostAuthorNick();
            case "lastPostDate":
                  return oneTopic.getLastPostDateFormatted();
                  if (match.Value==stringPlaceholderOne) {
                        return oneTopic.getReplyCount().ToString();
            return match.Value; // set this to "" if you want all undknown placeholders to be deleted

            listCode.Append(Regex.Replace(forumTemplate.getLoopCode(), @"\[(?<placeholder>[^\]]*)\]", new MatchEvaluator(ReplacePlaceholder)));


Author Comment

ID: 12114902
This is a perfect solution, thank you!
Unfortunatly I can't give your more points than 500 total :(

Thanks again (sorry for the delay with the points).
LVL 14

Expert Comment

ID: 12115859
Tanks for grading the question!

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
defining NULL or 0 10 51
How do I get the up & down arrow keys to navigate in an Autocomplete textbox list. 3 49
Name Space error VS2015 1 37
Set custom font WPF 2 21
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question