Convert string data to float array, string must be in the game "1.5, 3.534, 8.76, 7.49", etc. - CSharp System

CSharp examples for System:String Convert

Description

Convert string data to float array, string must be in the game "1.5, 3.534, 8.76, 7.49", etc.

Demo Code


using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.Collections;
using System;/*w ww .  ja v  a2s  .c o m*/

public class Main{
        /// <summary>
        /// Convert string data to float array, string must be in the game
        /// "1.5, 3.534, 8.76, 7.49", etc. WriteArrayData is the complementar
        /// function.
        /// </summary>
        /// <returns>float array, will be null if string is invalid!</returns>
        static public float[] ConvertStringToFloatArray( string s )
        {
            // Invalid?
            if ( s == null || s.Length == 0 )
                return null;

            string[] splitted = s.Split( new char[] { ' ' } );
            float[] ret = new float[ splitted.Length ];
            for ( int i = 0; i < ret.Length; i++ )
                if ( String.IsNullOrEmpty( splitted[ i ] ) == false )
                {
                    try
                    {
                        ret[ i ] = Convert.ToSingle( splitted[ i ],
                            CultureInfo.InvariantCulture );
                    } // try
                    catch { } // ignore
                } // for if (String.IsNullOrEmpty)
            return ret;
        } // ConvertStringToIntArray(str)
}

Related Tutorials