What is the fastest way of converting an array of floats to string? [duplicate]
What is the fastest way of converting an array of floats into string in C#?
If my array contains this { 0.1, 1.1, 1.0, 0.2 }
Then I want each entry to converted to a string with value separated by a white space, i.e. "0.1 1.1 1.0 0.2"
I would go for the most readable string.Join
which also should have sufficient performance in most cases. Unless there is a real issue, I would not run my own:
float[] values = { 1.0f, 2.0f, 3.0f };
string s = string.Join(" ", values);
It might be that I misread your question, so in case you want an enumeration of string
go with the other answers.
To be more explicit, call float.ToString()
manually and then string.Join()
to separate each result with a space:
var array = new float[] { 0.1, 1.1, 1.0, 0.2 };
string result = String.Join(" ", array.Select(f => f.ToString(CultureInfo.CurrentCulture));
btw,
in .NET 2.0/3.0/3.5 there only single String.Join(string, string[])
but in .NET 4.0 there is also String.Join<T>(string, IEnumerable<T>)
@0xA3 uses method from .NET 4.0. Mine too. So for earlier versions use array.Select(..).ToArray()
You can do it like this:
var floatsAsString = yourFloatArray.Select(f => f.ToString(CultureInfo.CurrentCulture));
float[] arr = { 1.0f, 2.1f };
var str = arr.Select(x => x.ToString()).ToArray();
or use rray.ConvertAll
public static string FloatFToString(float f)
{
return f.ToString();
}
float[] a = { 1.0f, 2.1f };
var res = Array.ConvertAll(a, new Converter<float, string>(FloatFToString));
I like approach with using Enumerable.Aggregate method:
float[] array = new float[] { .1f, .2f, .3f, .4f, .5f };
string s = array.AsEnumerable().Aggregate<float, string, string>("", (a, e) => a += string.Format(" {0}", e), r => r.Trim());
Works fast.
精彩评论