我建议第一Split
和才把Replace
:
string text = "4'-8\"x5/16\"x20'-8 13/16";
string[] items = text
.Split('x')
.Select(item => item
.Replace("'", "*12")
.Replace("-", "+")
.Replace("x", "+")
.Replace(" ", "+")
.Replace(@"""", ""))
.ToArray();
测试:
Console.Write(string.Join(Environment.NewLine, items));
结果:
4*12+8
5/16
20*12+8+13/16
如果你希望将结果格式化了成公式与a
,b
,c
...(因为你已经把它的问题):
string[] items = text
.Split('x')
.Select(item => item
.Replace("'", "*12")
.Replace("-", "+")
.Replace("x", "+")
.Replace(" ", "+")
.Replace(@"""", ""))
.Select((v, i) => $"{(char)('a' + i)} = ({v})")
.ToArray();
string formula =
string.Join(Environment.NewLine, items) + Environment.NewLine +
$"{(char) ('a' + items.Length)} = " +
string.Join(" + ", Enumerable.Range('a', items.Length).Select(c => $"{(char) (c)}"));
Console.Write(formula);
结果:
a = (4*12+8)
b = (5/16)
c = (20*12+8+13/16)
d = a + b + c
最后,你所提到的
值分别各子表达式和最终十进制数
和简单的公式,你可以尝试DataTable.Compute:
string formula;
using (DataTable dt = new DataTable()) {
string[] items = text
.Split('x')
.Select(item => item
.Replace("'", "*12")
.Replace("-", "+")
.Replace("x", "+")
.Replace(" ", "+")
.Replace(@"""", ""))
.ToArray();
formula =
string.Join(Environment.NewLine, items
.Select((v, i) => $"{(char) ('a' + i)} = ({v}) = {dt.Compute(v, null)}")) +
Environment.NewLine +
$"{(char) ('a' + items.Length)} = " +
string.Join(" + ", Enumerable.Range('a', items.Length).Select(c => $"{(char) (c)}")) +
$" = {items.Sum(item => Convert.ToDecimal(dt.Compute(item, null)))}";
}
Console.Write(formula);
结果:
a = (4*12+8) = 56
b = (5/16) = 0.3125
c = (20*12+8+13/16) = 248.8125
d = a + b + c = 305.1250
我执行你的(*修正*: 'string text =“4'-8 \”x5/16 \“x20'-8 13/16”;')code and I've got''4 * 12 + 8 + 5/16 + 20 * 12 + 8 +13/16“'作为结果。 –
当b = 8 + 5/16时,为什么a = 4 * 12 + 8和b = 5/16而不是a = 4 * 12? –
@DmitryBychenko你是对的字符串文本表达。我需要分开这些值并显示为不同的十进制值。从表达式考虑它的宽度,厚度和长度。 –