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"
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.
float.ToString()
for each element in the array
Oct 20, 2010 at 10:26
string s = string.Join(" ", values.Select(f => f.ToString()).ToArray())
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.
String.Concat
and String.Format
definitely is very inefficient
Oct 20, 2010 at 11:13
String.Join
uses StringBuilder
internally that's much more efficient because of strings immutability in .NET.
Oct 20, 2010 at 12:54