1

I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.

Hopefully I have provided sufficient information.

4

5 回答 5

2
Math.Round(
    double.Parse(
       "[11.8%]".Split(new [] {"[", "]", "%"}, 
       StringSplitOptions.RemoveEmptyEntries)[0]))
于 2013-01-06T14:46:41.090 回答
1

为什么不使用正则表达式?

在此示例中,我假设括号内的值始终是带小数的双精度数。

string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
于 2013-01-06T14:45:58.117 回答
0

使用正则表达式 (Regex) 在一个括号内查找所需的单词。这是您需要的代码:使用 foreach 循环删除 % 并转换为 int。

List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, @"\[(?<tag>[^\]]*)\]")){
   s = s.TrimEnd('%');
   myValues.Add(Math.Round(Convert.ToDouble(s)));
}
于 2013-01-06T14:46:32.703 回答
0
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
于 2013-01-06T14:50:52.843 回答
0

如果您可以确保括号之间的内容是 <decimal>% 的形式,那么这个小函数将返回第一组括号之间的值。如果需要提取多个值,则需要对其进行一些修改。

public decimal getProp(string str)
{
    int obIndex = str.IndexOf("["); // get the index of the open bracket
    int cbIndex = str.IndexOf("]"); // get the index of the close bracket
    decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
    return Math.Round(d); // return the number rounded to the nearest integer
}

例如getProp("I like cookies [66.7%]")给出Decimal数字 67

于 2013-01-06T14:51:16.417 回答