I've read a file into a variable in my c# project and want to convert it into an array of floats.
Here's a sample of the txt file:
-5.673
10.543
-0.322
10.048
The file contains a number, followed by a blank line and another number.
I've used the following code to read the file into my project:
var numbers = File.ReadAllLines(@"numbers.txt")
How would i convert numbers
into a float array?
Thanks
You can use Linq
and float.Parse()
:
var floats = numbers.Where(s => s != String.Empty).Select(s => float.Parse(s, CultureInfo.InvariantCulture)).ToArray();
But if you have incorrect data in file you will get exception. To check if value is correct float
use float.TryParse()
.
变量var
的类型是String[]
因此在这种情况下,您可以从数组的偶数位置获取值,然后转换为float
。
Your program should loop through each line in the file which are currently stored in the numbers
variable, which is of type String[]
, check if the value of the line is empty, and if not, convert it to a float and add it to our array of floats.
Bringing this all together would look something like this:
string[] numbers = File.ReadAllLines(@"numbers.txt");
// Create a list we can add the numbers we're parsing to.
List<float> parsedNumbers = new List<float>() ;
for (int i = 0; i < numbers.Length; i++)
{
// Check if the current number is an empty line
if (numbers[i].IsNullOrEmpty())
{
continue;
}
// If not, try to convert the value to a float
if (float.TryParse(numbers[i], out float parsedValue))
{
// If the conversion was successful, add it to the parsed float list
parsedNumbers.Add(parsedValue);
}
}
// Convert the list to an array
float[] floatArray = new float[parsedNumbers.Length];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.