CSharp examples for System:String Start End
Ensures a string ends with a specific string.
// Copyright ? 2011, Grid Protection Alliance. All Rights Reserved. using System.Text.RegularExpressions; using System.Text; using System.IO;//from w w w. ja v a2s . com using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using System; public class Main{ /// <summary> /// Ensures a string ends with a specific string. /// </summary> /// <param name="value">Input string to process.</param> /// <param name="endString">The string desired at string's end.</param> /// <returns>The sent string with string at the end.</returns> public static string EnsureEnd(this string value, string endString) { if (string.IsNullOrEmpty(value)) return ""; if (string.IsNullOrEmpty(endString)) return value; if (value.EndsWith(endString)) return value; else return string.Concat(value, endString); } /// <summary> /// Ensures a string ends with a specific character. /// </summary> /// <param name="value">Input string to process.</param> /// <param name="endChar">The character desired at string's end.</param> /// <param name="removeRepeatingChar">Set to <c>true</c> to ensure one and only one instance of <paramref name="endChar"/>.</param> /// <returns>The sent string with character at the end.</returns> public static string EnsureEnd(this string value, char endChar, bool removeRepeatingChar) { if (string.IsNullOrEmpty(value)) return ""; if (endChar == 0) return value; if (value[value.Length - 1] == endChar) { if (removeRepeatingChar) { int i = LastIndexOfRepeatedChar(value.Reverse(), endChar, 0); return value.Substring(0, value.Length - i); } return value; } else return string.Concat(value, endChar); } /// <summary> /// Ensures a string ends with a specific character. /// </summary> /// <param name="value">Input string to process.</param> /// <param name="endChar">The character desired at string's end.</param> /// <returns>The sent string with character at the end.</returns> public static string EnsureEnd(this string value, char endChar) { return EnsureEnd(value, endChar, false); } /// <summary> /// Reverses the order of the characters in a string. /// </summary> /// <param name="value">Input string to process.</param> /// <returns>The reversed string.</returns> public static string Reverse(this string value) { // Experimented with several approaches. This is the fastest. // Replaced original code that yielded 1.5% performance increase. // This code is faster than Array.Reverse. if (string.IsNullOrEmpty(value)) return ""; char[] arrChar = value.ToCharArray(); char temp; int arrLength = arrChar.Length; int j; // Works for odd and even length strings since middle char is not swapped for an odd length string for (int i = 0; i < arrLength / 2; i++) { j = arrLength - i - 1; temp = arrChar[i]; arrChar[i] = arrChar[j]; arrChar[j] = temp; } return new string(arrChar); } }