I have a file with numbers saved as strings. I am looking to load this data as a char[] then convert this array to an integer value. I have several values to load and am trying to avoid the overhead of creating thousands of temp strings..
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There's a couple of ways:
Convert.ToInt32
[MSDN]int.Parse
[MSDN]Although, these methods deal with
string
objects, notchar[]
. In C#, most of the time, you don't deal withchar[]
like you do in C because of the built-instring
type [MSDN].Yup
If you absolutely must convert the strings to character arrays (not sure why), you can use:
On a further note...
Is there a particular reason to use a
char[]
instead of just reading strings from the file? You will need astring
to convert to anint
anyway (using the standard conversion methods), so it seems like a wasted step.You should only need to create one string for each string you read from the file. I don't know what other processing is involved here, but reading a string from the file and then converting to an
int
will not create needless temporaries.If you are performing a large/unknown number of string concatenations then you should use a
StringBuilder
to build your input as it acts as a mutable string under the covers (initialize it to a large enough size when creating it as well). Even still, it will (should) take far longer to read the data from disk then it will take to create these strings.basically
Which is from http://www.csharptricks.com/blog/2006/09/string-to-integer-in-c-net.html with the string replaced with char[]
here is also a possible implementation of atoi()