I’m having a brain fart..what am I doing wrong …my array is off?
public static string CleanBadwordsFromString(string text) {
string badWords = "bunch,of,words,that,do,not,need,to,be,seen";
string[] badChars = badWords.Split(',');
string[] words = text.Split(' ');
int iLength = 0;
string sAttachtoEnd = null;
string cleanedString = "";
int x = 0;
int i = 0;
//loop through our array of bad words
for (i = 0; i <= badChars.Length; i++)
{
//get the length of the bad word
iLength = badChars[i].Length;
//we are going to keep the first letter of the bad word and replace all the other
//letters with *, so we need to find out how many * to use
for (x = 1; x <= iLength - 1; x++)
{
sAttachtoEnd = sAttachtoEnd + "*";
}
//replace any occurences of the bad word with the first letter of it and the
//rest of the letters replace with *
foreach (string s in words)
{
cleanedString =cleanedString + s.Replace(s, s.Substring(s.Length-1) + sAttachtoEnd); //should be: shit = s***
}
sAttachtoEnd = "";
}
return cleanedString;
}
I tried to run your code with the
i < badChar.Lengthsolution and, even though it ran without error, the result was not what I expected.I tried to run this:
And I got:
n****r****t****:****,****,****r****?****n*r*t*:*,*,*r*?*n****r****t****:****,****,****r****?****n***r***t***:***,***,***r***?***n*r*t*:*,*,*r*?*n**r**t**:**,**,**r**?**n***r***t***:***,***,***r***?***n*r*t*:*,*,*r*?*n*r*t*:*,*,*r*?*n***r***t***:***,***,***r***?***Obviously that’s not right.
I know your question was about the array index, but I figured that you’d want to then get the code to work correctly beyond that. So I thought how I might rewrite to make it work. Here’s what I came up with:
Now my result is:
S*** or n** s***: B****, b****ing, or b****ed?And that looks pretty good to me.
My approach doesn’t rely on splitting on space so will pick up punctuation and suffixes. It also works if the source text contains uppercase.