去除空白:C# [英] Removing White Space: C#

查看:18
本文介绍了去除空白:C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试删除存在于String input 中的空格.我的最终目标是创建一个中缀计算器,但我在解析输入表达式时遇到了问题.

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.

在我看来,解决这个问题的简单方法是使用 Regular Expression 函数,即 Regex.Replace(...)

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, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)");

假设用户输入中缀表达式 (2 + 3) * 4,我希望这会将字符串分解为数组 {(, 2, +, 3, ), *, 4};但是,调试后,我得到以下输出:

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!

推荐答案

感谢您的所有回复,我找到了我一直在寻找的解决方案.

I found the solution I was looking for thanks to all of your replies.

// Ignore all whitespace within the expression.
infixExp = Regex.Replace(infixExp, @"\s+", String.Empty);

// Seperate the expression based on the tokens (, ), +, -, 
// *, /, and ignore any of the empty Strings that are added
// due to duplicates.
string[] substrings = Regex.Split(infixExp, @"([()+*/-])");
substrings = substrings.Where(s => s != String.Empty).ToArray();

通过这样做,它根据常规数学运算符(+、-、*、/)和括号将字符串的字符分成几部分.执行此操作后,它会消除 substrings

By doing this it seperates the characters of the String into parts based on the regular mathematical operators (+, -, *, /) and parenthesis. After doing this it eliminates any remaining empty Strings within the substrings

这篇关于去除空白:C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆