Link to home
Start Free TrialLog in
Avatar of Smoerble
SmoerbleFlag for Germany

asked on

Best way for this string.replace?

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
Avatar of eternal_21
eternal_21

Why would "stringPlaceholderOne" be null?
Or, sorry: An empty string?
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.
Avatar of Smoerble

ASKER

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
SOLUTION
Avatar of AvonWyss
AvonWyss
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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).
Tanks for grading the question!