我想解析一个字符串,只返回括号之间的值,例如[10.2%]
。然后我需要去掉"%"
符号并将小数转换为向上/向下舍入的整数。因此,[10.2%]
最终会成为10
。并且,[11.8%]
最终会成为12。
希望我提供了足够的信息。
答案 0 :(得分:2)
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
答案 1 :(得分: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(".", ","));
答案 2 :(得分: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)));
}
答案 3 :(得分:0)
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
答案 4 :(得分:0)
如果您可以确保括号之间的内容的格式为&lt; decimal&gt;%,则此小函数将返回第一组括号之间的值。如果您需要提取多个值,则需要稍微修改它。
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