简体   繁体   English

如何从一个字符串中提取多个数字?

[英]How do I extract multiple numbers from a string?

I want to extract three doubles from this string.我想从这个字符串中提取三个双打。 The is a space between the numbers but nothing else.是数字之间的空格,但没有别的。

string A = "3.1415 2.71828 1729.0"字符串 A = "3.1415 2.71828 1729.0"

Use the Split() method.使用Split()方法。

string[] nums = A.Split(' ');

Then do the conversion.然后进行转换。

Updated: Changed double quotes to single quotes更新:将双引号更改为单引号

You can do this by using the String.Split() method combined with LINQ:您可以通过将 String.Split() 方法与 LINQ 结合使用来完成此操作:

string A = "3.1415 2.71828 1729.0";
double[] numbers = A.Split().Select(x=>double.Parse(x.Replace(".",","))).ToArray();

In the above example the decimal numbers in string A are converted from string to double and stored in a double array, but if you want to store your decimal numbers as separate strings in a string array then use:在上面的示例中,字符串A中的十进制数从string转换为double并存储在 double 数组中,但如果要将十进制数作为单独的字符串存储在字符串数组中,请使用:

string[] numbers = A.Split();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM