Solved

Best way for this string.replace?

Posted on 2004-08-20
9
201 Views
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...
listCode.Append(forumTemplate.getLoopCode().Replace(
    "[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.

Question:
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
0
Comment
Question by:Smoerble
  • 3
  • 3
  • 2
9 Comments
 
LVL 10

Expert Comment

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

Expert Comment

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

Expert Comment

by:eternal_21
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.
0
 

Author Comment

by:Smoerble
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?
Thx
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 14

Assisted Solution

by:AvonWyss
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)
    stringPlaceholderOne=Guid.NewGuid().ToString();

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.
0
 
LVL 14

Accepted Solution

by:
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();
            default:
                  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)));

0
 

Author Comment

by:Smoerble
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).
0
 
LVL 14

Expert Comment

by:AvonWyss
ID: 12115859
Tanks for grading the question!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now