我有一个大字符串,字符串中有一系列浮点。典型的字符串将具有 Item X $4.50 Description of item\r\n\r\n Item Z $4.75...
文本确实没有押韵或原因。我已经有了最低的值,我需要找到字符串中的所有值。因此,如果它是 10.00
,它将找到 10.05
或更小的每个值。我假设需要某种正则表达式来查找值,然后我可以将它们放入数组中然后对它们进行排序。
因此,找到这些值中哪些值符合我的标准,就像这样。
int [] array;
int arraysize;
int lowvalue;
int total;
for(int i = 0; i<arraysize; ++i)
{
if(array[i] == lowvalue*1.05) ++total;
}
我的问题是在数组中获取这些值。我已阅读this但 d+ 并不真正适用于浮点。
最佳答案
您应该使用正则表达式:
Regex r = new RegEx("[0-9]+\.[0-9]+");
Match m = r.Match(myString);
类似这样的事情。然后你就可以使用:
float f = float.Parse(m.value);
如果你需要一个数组:
MatchCollection mc = r.Matches(myString);
string[] myArray = new string[mc.Count];
mc.CopyTo(myArray, 0);
编辑
我刚刚为你创建了一个小示例应用程序,乔。我编译了它,并且使用您问题中的输入行在我的机器上运行良好。如果您遇到问题,请发布您的输入字符串,以便我可以尝试一下。这是我写的代码:
static void Main(string[] args)
{
const string InputString = "Item X $4.50 Description of item \r\n\r\n Item Z $4.75";
var r = new Regex(@"[0-9]+\.[0-9]+");
var mc = r.Matches(InputString);
var matches = new Match[mc.Count];
mc.CopyTo(matches, 0);
var myFloats = new float[matches.Length];
var ndx = 0;
foreach (Match m in matches)
{
myFloats[ndx] = float.Parse(m.Value);
ndx++;
}
foreach (float f in myFloats)
Console.WriteLine(f.ToString());
// myFloats should now have all your floating point values
}
关于c# - 在大字符串中查找浮点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6754545/