+ 1

Help with Looping through arrays in C# please

I've been looking all day online for the answer to this question, but everything I try doesn't seem to work. So I'm working on a word censurer, and I have a string of words that is turned into an array of words in line 1 of the code snippet. Everything works fine, except for this snippet of code: string[] BadWordsList = EveryBadWord.Split(' '); for (int i = 0; i <= BadWordsList.Length; i++) { string ThisWord = MalasPalabrasList[i]; CensoredText = CensoredText.Replace(ThisWord, "X"); } Debug.Log(CensoredText); When I use the text field in Unity and enter a text, it works fine, but when it gets to that part where it is supposed to replace bad words with an X (for later counting the number of Xs and knowing how many bad words were used). It marks an error that says: IndexOutOfRangeException: Index was outside the bounds of the array. manager.CheckText () (at Assets/manager.cs:173) I don't know what to do. How can I loop through the array to check the number of words that match the array and the text so it later returns a variable with all the words censured?

5th Nov 2019, 12:44 AM
Octavio Aguayo
Octavio Aguayo - avatar
2 Réponses
+ 1
you could even split input in the start of the method removing all special char and space and then checking if that array contains any of the bad words and if not just return original string.
5th Nov 2019, 12:27 PM
Stephen Frey
0
im sure this isnt the best way but this should work.. Public String FilterWords(string Input) { String[] tempArray = input.split(' '); string[] newPhraseArr = new newPhraseArr[tempArray.Length]; Int y = 0; foreach(string s in tempArray) { string word = s; string wordLC = word.ToLower(); Char[] temp = new temp[word.length]; for(int x = 0; x < badWords.Length;x++) { If(wordLC == badWords[x]) { Int t = 0; foreach(Char c in Word) { temp[t] = '*'; t++; } t = 0; word = String.Join("", temp); } newPhraseArr[y] = word; y++; } } Return String.Join(" ", newPhraseArr); } let us know if it works!
5th Nov 2019, 12:19 PM
Stephen Frey