Write into space string, useful for writing parameters without knowing the length of each string, e.g. when writing numbers (-1, 1.45, etc.). - CSharp System

CSharp examples for System:String Number

Description

Write into space string, useful for writing parameters without knowing the length of each string, e.g. when writing numbers (-1, 1.45, etc.).

Demo Code


using System.Text;
using System.Globalization;
using System.Collections.Specialized;
using System.Collections;
using System;//from  w ww  .  j a  va2 s. c  om

public class Main{
        /// <summary>
        /// Write into space string, useful for writing parameters without
        /// knowing the length of each string, e.g. when writing numbers
        /// (-1, 1.45, etc.). You can use this function to give all strings
        /// the same width in a table. Maybe there is already a string function
        /// for this, but I don't found any useful stuff.
        /// </summary>
        static public string WriteIntoSpaceString( string message, int spaces )
        {
            if ( message == null )
                throw new ArgumentNullException( "message",
                    "Unable to execute method without valid text." );

            // Msg is already that long or longer?
            if ( message.Length >= spaces )
                return message;

            // Create string with number of specified spaces
            char[] ret = new char[ spaces ];

            // Copy data
            int i;
            for ( i = 0; i < message.Length; i++ )
                ret[ i ] = message[ i ];
            // Fill rest with spaces
            for ( i = message.Length; i < spaces; i++ )
                ret[ i ] = ' ';

            // Return result
            return new string( ret );
        } // WriteIntoSpaceString(message, spaces)
}

Related Tutorials