Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting unexpected results with StringBuilder and .replace?

I’m trying to find specific criteria (dogsWildcard, catsWildcard, birdsWildcard) in a string (wildCard) and then modify the string so it has a number associated with the criteria.

For example, I want the cold below to return: "*DOGS 111 *CATS 222 *BIRDS 333"

However, it’s returning something that looks like: "*CATS *DOGS 222 *BIRDS*DOGS 111 *EVENTS *BIRDS*BIRDS *DOGS *CATS 333"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


public string ProcessMerchantRefNbr()
{
var wildCard = "*DOGS *CATS *BIRDS";

string catsWildcard = "*CATS";
string dogsWildcard = "*DOGS";
string birdsWildcard = "*BIRDS";

var dogId = "111";
var catId = "222";
var birdId = "333";

var strMerchantRefNbr = new StringBuilder();

if (wildCard.Contains(catsWildcard)) strMerchantRefNbr.Append($"{catsWildcard} {wildCard.Replace(catsWildcard, catId)}");

if (wildCard.Contains(dogsWildcard)) strMerchantRefNbr.Append($"{dogsWildcard} {wildCard.Replace(dogsWildcard, dogId)}");

if (wildCard.Contains(birdsWildcard)) strMerchantRefNbr.Append($"{birdsWildcard} {wildCard.Replace(birdsWildcard, birdId)}");

return strMerchantRefNbr.ToString()
}

What am I doing wrong?

>Solution :

Simply you don’t need the Replace.

var strMerchantRefNbr = new StringBuilder();

if (wildCard.Contains(catsWildcard)) strMerchantRefNbr.Append($"{catsWildcard} {catId} ");
if (wildCard.Contains(dogsWildcard)) strMerchantRefNbr.Append($"{dogsWildcard} {dogId} ");
if (wildCard.Contains(birdsWildcard)) strMerchantRefNbr.Append($"{birdsWildcard} {birdId} ");

// strMerchantRefNbr.ToString(): *CATS 222 *DOGS 111 *BIRDS 333 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading