Removing White Space: C#

2019-08-29 10:01发布

I am trying to remove white space that exists in a String input. My ultimate goal is to create an infix evaluator, but I am having issues with parsing the input expression.

It seems to me that the easy solution to this is using a Regular Expression function, namely Regex.Replace(...)

Here's what I have so far..

infixExp = Regex.Replace(infixExp, "\\s+", string.Empty);
string[] substrings = Regex.Split(infixExp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)");

Assuming the user inputs the infix expression (2 + 3) * 4, I would expect that this would break the string into the array {(, 2, +, 3, ), *, 4}; however, after debugging, I am getting the following output:

infixExp = "(2+3)*7"
substrings = {"", (, 2, +, 3, ), "", *, 7}

It appears that the white space is being properly removed from the infix expression, but splitting the resulting string is improper.

Could anyone give me insight as to why? Likewise, if you have any constructive criticism or suggestions, let me know!

7条回答
叛逆
2楼-- · 2019-08-29 10:33

Please, ditch Regex. There are better tools to use. You can use String.Trim(), .TrimEnd(), and .TrimStart().

string inputString = "   asdf    ";
string output = inputString.Trim();

For whitespace within the string, use String.Replace.

string output2 = output.Replace(" ", "");

You will have to expand this to other whitespace characters.

查看更多
登录 后发表回答