Convert string data to int array, string must be in the game "1, 3, 8, 7", etc. - CSharp System

CSharp examples for System:String Convert

Description

Convert string data to int array, string must be in the game "1, 3, 8, 7", etc.

Demo Code


using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.Collections;
using System;//from   ww  w  .  j  a v  a 2s .  c  o  m

public class Main{
        #endregion

        #region Convert methods
        /// <summary>
        /// Convert string data to int array, string must be in the game
        /// "1, 3, 8, 7", etc. WriteArrayData is the complementar function.
        /// </summary>
        /// <returns>int array, will be null if string is invalid!</returns>
        static public int[] ConvertStringToIntArray( string s )
        {
            // Invalid?
            if ( s == null || s.Length == 0 )
                return null;

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

Related Tutorials