You are reading CSharp - Replace embedded Wildcard in String. You can leave a comment or trackback this post.
Posted on February 2nd, 2006 by gernot.
Categories: CSharp.
A small method for replacing an embedded wildcard in a string.
String: [GG] is 24 [Y] old
[GG] should be replaced with Gernot Goluch and [Y] with year
One possible usage would be including different IDs of xml elements or db entries in other entries by using wildcard delimiters in some content of the entry.
E.g. xml processing
‹testNode id=“123″›BlaBla‹/testNode›
‹testNode id=”456″›BlaBla and [123] is really dumb content‹/testNode›
After processing the content of testNode with id “456″ the content would be:
“BlaBla and Blabla is really dumb content”
The method call for the simple example above.
replaceWildCardInString(“[GG] is 24 [Y] old”,new char[] {‘[', ']‘});
The method for the simple example above.
public string replaceWildCardInString(string _string, char[] _wildCard) {
if (_string.IndexOf(_wildCard[0]) == -1) return _string;
else {
//split string and get content to replace
string[] contentSplit = _string.Split(_wildCard);
//What is inbetween the wildcards
string contentToReplace = contentSplit[1];
//The ‘real’ content
//***Add Code here how to get the real content***
//E.g.: very simple. Possible inclusion of db or xml query/method call
string contentReplace = “”;
if (contentToReplace.Equals(“GG”)) contentReplace = “Gernot Goluch”;
else if (contentToReplace.Equals(“Y”)) contentReplace = “year”;
//replace the wildcard with the ‘real’ content
//and check if other wildcards are in the content
WildCardClass wcc = new WildCardClass();
return wcc.replaceWildCardInString(
_string.Replace(
_wildCard[0] + contentToReplace + _wildCard[1]
, contentReplace)
, _wildCard);
}
}
0 comments.
Comments can contain some xhtml. Names and emails are required (emails aren't displayed), url's are optional.