Search code examples
c#special-characterstrim

Special characters Regex


Hello I'm try to remove special characters from user inputs.

        public void fd()
        {
            string output = "";
            string input = Console.ReadLine();
            char[] charArray = input.ToCharArray();

            foreach (var item in charArray)
            {

                if (!Char.IsLetterOrDigit(item))
                {

                   \\\CODE HERE                    }

            }

            output = new string(trimmedChars);
            Console.WriteLine(output);
        }

At the end I'm turning it back to a string. My code only removes one special character in the string. Does anyone have any suggestions on a easier way instead


Solution

  • The problem with your code is that you are taking the data from charArray and putting the result in trimmedChars for each change that you make, so each change will ignore all previous changes and work with the original. At the end you only have the last change.

    Another problem with the code is that you are using IndexOf to get the index of a character, but that will get the index of the first occurance of that character, not the index where you got that character. For example when you are at the second ! in the string "foo!bar!" you will get the index of the first one.

    You don't need to turn the string into an array to work with the characters in the string. You can just loop through the index of the characters in the string.

    Note that you should also check the value of the index when you are looking at the characters before and after, so that you don't try to look at characters that are outside the string.

    public void fd() {
      string input = Console.ReadLine();
      int index = 0;
      while (index < input.Length) {
        if (!Char.IsLetterOrDigit(input, index) && ((index == 0 || !Char.IsLetterOrDigit(input, index - 1)) || (index == input.Length - 1 || !Char.IsLetterOrDigit(input, index + 1)))) {
          input = input.Remove(index, 1);
        } else {
          index++;
        }
      }
      Console.WriteLine(input);
    }