Pads a string making it always the provided length. Trims if string is too long. - CSharp System

CSharp examples for System:String Strip

Description

Pads a string making it always the provided length. Trims if string is too long.

Demo Code


using System.Xml;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.IO;/*from w w  w .ja  v  a  2 s  . c  o m*/
using System.Globalization;
using System.Data;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
		/// Pads a string making it always the provided length. Trims if string is too long.
		/// </summary>
		/// <param name="value">String to pad/trim.</param>
		/// <param name="length">Length the string should be.</param>
		/// <returns>String containing pads, if it is longer than requested length it will be trimmed.</returns>
		public static string FixLengthString(this string value, int length)
		{
			const string padding = " ";

			if (string.IsNullOrEmpty(value))
			{
				StringBuilder builder = new StringBuilder(length);

				for (int i = 0; i < length; i++)
				{
					builder.Append(padding);
				}

				return builder.ToString();
			}

			if (value.Length < length)
			{
				StringBuilder builder = new StringBuilder(length);
				builder.Append(value);

				int paddingCount = length - value.Length;

				for (int i = 0; i < paddingCount; i++)
				{
					builder.Append(padding);
				}

				return builder.ToString();
			}

			return value.Length > length ? value.Substring(0, length) : value;
		}
        /// <summary>
		/// Checks if a string is null or empty
		/// </summary>
		/// <param name="value" />
		/// <returns>True if null or empty, false otherwise</returns>
		public static bool IsNullOrEmpty(this string value)
		{
			return string.IsNullOrEmpty(value);
		}
        /// <summary>
		/// Appends a string onto another
		/// </summary>
		/// <param name="value" />
		/// <param name="stringToAppend" />
		/// <returns />
		public static string Append(this string value, string stringToAppend)
		{
			string returnString = value;

			if (returnString.IsNullOrWhiteSpace())
			{
				returnString = string.Empty;
			}

			returnString += stringToAppend;

			return returnString;
		}
}

Related Tutorials