C# String Library

Overview:

Recently I was doing some coding and switching back and forth between a project written in PHP and another in C#. Having rebuilt my PHP muscle memory after a couple months of neglect, I instinctively called nl2br on a string in C#. Obviously instead of the desired result, I got a compliation error. Like a tiny bolt of lightning, it struck me that there are a number of useful functions in the PHP string library that are missing in C#'s implentation of String. This library is the result of that wee epiphany.

The intent of the article is to introduce you to the PHP inspired String Library for .Net. I did not port over all the PHP String functions --as some of the methods in PHP's library are a little too exotic for my taste --such as the levenshtein function. or the even more questionable str_rot13. I am just not sure when I'd need those, so I left them out. (In fact, if anyone has any examples of when they used str_rot13, please let me know!) I also added a few methods that are not in PHP's library but that I thought would be helpful --e.g. TrimIntraWords, FilterWords, etc.

Methods

Below is a list of the method names and descriptions in the string library. I did not give the signatures, but many of these have several overloads. Also, I did not keep the PHP method names as those names do not conform to .Net best practices. You can view all the methods, their overloads, and documentation by clicking on the "View the Code" button below or by just downloading the .cs file.

  • Base64StringEncode: Base64 encodes a string.
  • Base64StringDecode: Decodes a Base64 string.
  • CaseInsenstiveReplace: A case insenstive replace function.
  • ReplaceFirst: Replaces the first occurence of a string with the replacement value. The Replace is case senstive. [The inclusion of this method and ReplaceLast was suggested by a reader's comment.]
  • ReplaceLast: Replaces the last occurence of a string with the replacement value. The replace is case senstive.
  • FilterWords: Removes all the words passed in the filter words parameters. The replace is NOT case sensitive.
  • HasWords: Checks the passed string to see if it contains any of the passed words. Not case-sensitive.
  • HtmlSpecialEntitiesEncode: A wrapper around HttpUtility.HtmlEncode.
  • HtmlSpecialEntitiesDecode: A wrapper around HttpUtility.HtmlDecode.
  • MD5String: MD5 encodes the passed string.
  • MD5VerifyString: Verifies a string against the passed MD5 hash.
  • PadLeftHtmlSpaces: Left pads the passed string using the HTML non-breaking space ( ) for the total number of spaces.
  • CaseInsenstiveReplace: Performs a case insenstive replace.
  • PadLeft: Left pads the passed string using the passed pad string for the total number of spaces. (It will not cut-off the pad even if it causes the string to exceed the total width.)
  • PadRightHtmlSpaces: Right pads the passed string using the HTML non-breaking space ( ) for the total number of spaces.
  • PadRight: Right pads the passed string using the passed pad string for the total number of spaces. (It will not cut-off the pad even if it causes the string to exceed the total width.)
  • RemoveNewLines: Removes the new line (\n) and carriage return (\r) symbols.
  • Reverse: Reverses the passed string.
  • SentenceCase: Converts a string to sentence case.
  • SpaceToNbsp: Converts all spaces to HTML non-breaking spaces.
  • StripTags: Removes all HTML tags from the passed string.
  • TitleCase: Converts a string to title case.
  • TrimIntraWords: Removes multiple spaces between words.
  • NewLineToBreak: Converts each new line (\n) and carriage return (\r) symbols to the HTML <br /> tag.
  • WordWrap: Wraps the passed string at the passed total number of characters (if cuttOff is true)or at the next whitespace (if cutOff is false). Uses the environment new linesymbol for the break text.

 

None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Security.Cryptography;
None.gif
using  System.Text;
None.gif
using  System.Text.RegularExpressions;
None.gif
using  System.Web;
None.gif
using  System.Xml;
None.gif
None.gif
namespace  CoreWebLibrary.String
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif   
/**//// <summary>
InBlock.gif   
/// Helper functions for String not already found in C#.
InBlock.gif   
/// Inspired by PHP String Functions that are missing in .Net.
ExpandedSubBlockEnd.gif   
/// </summary>

InBlock.gif   public static class StringHelper
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Base64 encodes a string.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">A string</param>
ExpandedSubBlockEnd.gif      
/// <returns>A base64 encoded string</returns>

InBlock.gif      public static string Base64StringEncode(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(input);
InBlock.gif         
return Convert.ToBase64String(encbuff);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Base64 decodes a string.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">A base64 encoded string</param>
ExpandedSubBlockEnd.gif      
/// <returns>A decoded string</returns>

InBlock.gif      public static string Base64StringDecode(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
byte[] decbuff = Convert.FromBase64String(input);
InBlock.gif         
return System.Text.Encoding.UTF8.GetString(decbuff);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// A case insenstive replace function.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to examine.</param>
InBlock.gif      
/// <param name="newValue">The value to replace.</param>
InBlock.gif      
/// <param name="oldValue">The new value to be inserted</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string CaseInsenstiveReplace(string input, 
InBlock.gif         
string newValue, string oldValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         Regex regEx 
= new Regex(oldValue, 
InBlock.gif            RegexOptions.IgnoreCase 
| RegexOptions.Multiline);
InBlock.gif         
return regEx.Replace(input, newValue);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Replaces the first occurence of a string with the replacement value. The Replace
InBlock.gif      
/// is case senstive
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to examine</param>
InBlock.gif      
/// <param name="oldValue">The value to replace</param>
InBlock.gif      
/// <param name="newValue">the new value to be inserted</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string ReplaceFirst(string input, string oldValue, string newValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         Regex regEx 
= new Regex(oldValue, RegexOptions.Multiline);
InBlock.gif         
return regEx.Replace(input, newValue, 1);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Replaces the last occurence of a string with the replacement value.
InBlock.gif      
/// The replace is case senstive.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to examine</param>
InBlock.gif      
/// <param name="oldValue">The value to replace</param>
InBlock.gif      
/// <param name="newValue">the new value to be inserted</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string ReplaceLast(string input, string oldValue, string newValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
int index = input.LastIndexOf(oldValue);
InBlock.gif         
if (index < 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
return input;
ExpandedSubBlockEnd.gif         }

InBlock.gif         
else
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            StringBuilder sb 
= new StringBuilder(input.Length - oldValue.Length + newValue.Length);
InBlock.gif            sb.Append(input.Substring(
0, index));
InBlock.gif            sb.Append(newValue);
InBlock.gif            sb.Append(input.Substring(index 
+ oldValue.Length, 
InBlock.gif               input.Length 
- index - oldValue.Length));
InBlock.gif            
InBlock.gif            
return sb.ToString();
ExpandedSubBlockEnd.gif         }

ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes all the words passed in the filter words 
InBlock.gif      
/// parameters. The replace is NOT case
InBlock.gif      
/// sensitive.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to search.</param>
InBlock.gif      
/// <param name="filterWords">The words to 
InBlock.gif      
/// repace in the input string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string FilterWords(string input, 
InBlock.gif         
params string[] filterWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.FilterWords(input, 
InBlock.gif            
char.MinValue, filterWords);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes all the words passed in the filter words 
InBlock.gif      
/// parameters. The replace is NOT case
InBlock.gif      
/// sensitive.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to search.</param>
InBlock.gif      
/// <param name="mask">A character that is inserted for each 
InBlock.gif      
/// letter of the replaced word.</param>
ExpandedSubBlockEnd.gif      
/// <param name="filterWords">The words to 

InBlock.gif      // repace in the input string.</param>
ExpandedSubBlockStart.gifContractedSubBlock.gif
      /**//// <returns>A string.</returns>
InBlock.gif      public static string FilterWords(string input, char mask, 
InBlock.gif         
params string[] filterWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
string stringMask = mask == char.MinValue ? 
InBlock.gif            
string.Empty : mask.ToString();
InBlock.gif         
string totalMask = stringMask;
InBlock.gif
InBlock.gif         
foreach (string s in filterWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            Regex regEx 
= new Regex(s, 
InBlock.gif               RegexOptions.IgnoreCase 
| RegexOptions.Multiline);
InBlock.gif
InBlock.gif            
if (stringMask.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               
for (int i = 1; i < s.Length; i++)
InBlock.gif                  totalMask 
+= stringMask;
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            input 
= regEx.Replace(input, totalMask);
InBlock.gif
InBlock.gif            totalMask 
= stringMask;
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
return input;
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Checks the passed string to see if has any of the 
InBlock.gif      
/// passed words. Not case-sensitive.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to check.</param>
InBlock.gif      
/// <param name="hasWords">The words to check for.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A collection of the matched words.</returns>

InBlock.gif      public static MatchCollection HasWords(string input, 
InBlock.gif         
params string[] hasWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         StringBuilder sb 
= new StringBuilder(hasWords.Length + 50);
InBlock.gif         
//sb.Append("[");
InBlock.gif

InBlock.gif         
foreach (string s in hasWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            sb.AppendFormat(
"({0})|"
InBlock.gif               StringHelper.HtmlSpecialEntitiesEncode(s.Trim()));
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
string pattern = sb.ToString();
InBlock.gif         pattern 
= pattern.TrimEnd('|'); // +"]";
InBlock.gif

InBlock.gif         Regex regEx 
= new Regex(pattern, 
InBlock.gif            RegexOptions.IgnoreCase 
| RegexOptions.Multiline);
InBlock.gif         
return regEx.Matches(input);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// A wrapper around HttpUtility.HtmlEncode
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to be encoded</param>
ExpandedSubBlockEnd.gif      
/// <returns>An encoded string</returns>

InBlock.gif      public static string HtmlSpecialEntitiesEncode(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return HttpUtility.HtmlEncode(input);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// A wrapper around HttpUtility.HtmlDecode
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to be decoded</param>
ExpandedSubBlockEnd.gif      
/// <returns>The decode string</returns>

InBlock.gif      public static string HtmlSpecialEntitiesDecode(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return HttpUtility.HtmlDecode(input);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// MD5 encodes the passed string
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to encode.</param>
ExpandedSubBlockEnd.gif      
/// <returns>An encoded string.</returns>

InBlock.gif      public static string MD5String(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
// Create a new instance of the 
InBlock.gif         
// MD5CryptoServiceProvider object.
InBlock.gif
         MD5 md5Hasher = MD5.Create();
InBlock.gif
InBlock.gif         
// Convert the input string to a byte 
InBlock.gif         
// array and compute the hash.
InBlock.gif
         byte[] data = md5Hasher.ComputeHash(
InBlock.gif            Encoding.Default.GetBytes(input));
InBlock.gif
InBlock.gif         
// Create a new Stringbuilder to collect the bytes
InBlock.gif         
// and create a string.
InBlock.gif
         StringBuilder sBuilder = new StringBuilder();
InBlock.gif
InBlock.gif         
// Loop through each byte of the hashed data 
InBlock.gif         
// and format each one as a hexadecimal string.
InBlock.gif
         for (int i = 0; i < data.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            sBuilder.Append(data[i].ToString(
"x2"));
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
// Return the hexadecimal string.
InBlock.gif
         return sBuilder.ToString();
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Verified a string against the passed MD5 hash.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to compare.</param>
InBlock.gif      
/// <param name="hash">The hash to compare against.</param>
InBlock.gif      
/// <returns>True if the input and the hash 
ExpandedSubBlockEnd.gif      
/// are the same, false otherwise.</returns>

InBlock.gif      public static bool MD5VerifyString(string input, string hash)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
// Hash the input.
InBlock.gif
         string hashOfInput = StringHelper.MD5String(input);
InBlock.gif
InBlock.gif         
// Create a StringComparer an comare the hashes.
InBlock.gif
         StringComparer comparer = StringComparer.OrdinalIgnoreCase;
InBlock.gif
InBlock.gif         
if (0 == comparer.Compare(hashOfInput, hash))
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
return true;
ExpandedSubBlockEnd.gif         }

InBlock.gif         
else
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
return false;
ExpandedSubBlockEnd.gif         }

ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Left pads the passed input using the HTML 
InBlock.gif      
/// non-breaking string entity (&nbsp;)
InBlock.gif      
/// for the total number of spaces.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number 
InBlock.gif      
/// to pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadLeftHtmlSpaces(string input, 
InBlock.gif         
int totalSpaces)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
string space = "&nbsp;";
InBlock.gif         
return PadLeft(input, space, totalSpaces * space.Length);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Left pads the passed input using the passed pad string
InBlock.gif      
/// for the total number of spaces.  It will not 
InBlock.gif      
/// cut-off the pad even if it 
InBlock.gif      
/// causes the string to exceed the total width.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="pad">The string to uses as padding.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number to 
InBlock.gif      
/// pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadLeft(string input, 
InBlock.gif         
string pad, int totalWidth)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.PadLeft(input, pad, totalWidth, false);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Left pads the passed input using the passed pad string
InBlock.gif      
/// for the total number of spaces.  It will 
InBlock.gif      
/// cut-off the pad so that  
InBlock.gif      
/// the string does not exceed the total width.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="pad">The string to uses as padding.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number to 
InBlock.gif      
/// pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadLeft(string input, string pad, 
InBlock.gif         
int totalWidth, bool cutOff)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
if (input.Length >= totalWidth)
InBlock.gif            
return input;
InBlock.gif
InBlock.gif         
int padCount = pad.Length;
InBlock.gif         
string paddedString = input;
InBlock.gif
InBlock.gif         
while (paddedString.Length < totalWidth)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            paddedString 
+= pad;
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
// trim the excess.
InBlock.gif
         if (cutOff)
InBlock.gif            paddedString 
= paddedString.Substring(0, totalWidth);
InBlock.gif
InBlock.gif         
return paddedString;
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Right pads the passed input using the HTML 
InBlock.gif      
/// non-breaking string entity (&nbsp;)
InBlock.gif      
/// for the total number of spaces.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number 
InBlock.gif      
/// to pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadRightHtmlSpaces(string input, 
InBlock.gif         
int totalSpaces)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
string space = "&nbsp;";
InBlock.gif         
return PadRight(input, space, totalSpaces * space.Length);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Right pads the passed input using the passed pad string
InBlock.gif      
/// for the total number of spaces.  It will not 
InBlock.gif      
/// cut-off the pad even if it 
InBlock.gif      
/// causes the string to exceed the total width.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="pad">The string to uses as padding.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number to 
InBlock.gif      
/// pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadRight(string input, 
InBlock.gif         
string pad, int totalWidth)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.PadRight(input, pad, totalWidth, false);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Right pads the passed input using the passed pad string
InBlock.gif      
/// for the total number of spaces.  It will cut-off
InBlock.gif      
/// the pad so that  
InBlock.gif      
/// the string does not exceed the total width.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to pad.</param>
InBlock.gif      
/// <param name="pad">The string to uses as padding.</param>
InBlock.gif      
/// <param name="totalSpaces">The total number to 
InBlock.gif      
/// pad the string.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A padded string.</returns>

InBlock.gif      public static string PadRight(string input, string pad, 
InBlock.gif         
int totalWidth, bool cutOff)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
if (input.Length >= totalWidth)
InBlock.gif            
return input;
InBlock.gif
InBlock.gif         
string paddedString = string.Empty;
InBlock.gif
InBlock.gif         
while (paddedString.Length < totalWidth - input.Length)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            paddedString 
+= pad;
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
// trim the excess.
InBlock.gif
         if (cutOff)
InBlock.gif            paddedString 
= paddedString.Substring(0
InBlock.gif               totalWidth 
- input.Length);
InBlock.gif
InBlock.gif         paddedString 
+= input;
InBlock.gif
InBlock.gif         
return paddedString;
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes the new line (\n) and carriage return (\r) symbols.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to search.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string RemoveNewLines(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.RemoveNewLines(input, false);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes the new line (\n) and carriage return 
InBlock.gif      
/// (\r) symbols.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to search.</param>
InBlock.gif      
/// <param name="addSpace">If true, adds a space 
InBlock.gif      
/// (" ") for each newline and carriage
InBlock.gif      
/// return found.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string RemoveNewLines(string input, 
InBlock.gif         
bool addSpace)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
string replace = string.Empty;
InBlock.gif         
if (addSpace)
InBlock.gif            replace 
= " ";
InBlock.gif
InBlock.gif         
string pattern = @"[\r|\n]";
InBlock.gif         Regex regEx 
= new Regex(pattern, 
InBlock.gif            RegexOptions.IgnoreCase 
| RegexOptions.Multiline);
InBlock.gif
InBlock.gif         
return regEx.Replace(input, replace);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Reverse a string.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to reverse</param>
InBlock.gif      
/// <returns>A string</returns>
InBlock.gif      
/// <remarks>Thanks to  Alois Kraus for pointing out an issue
InBlock.gif      
/// with an earlier version of this method and to Justin Roger's 
InBlock.gif      
/// site (http://weblogs.asp.net/justin_rogers/archive/2004/06/10/153175.aspx)
ExpandedSubBlockEnd.gif      
/// for helping me to improve that previous method.</remarks>

InBlock.gif      public static string Reverse(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
char[] reverse = new char[input.Length];
InBlock.gif         
for (int i = 0, k = input.Length - 1; i < input.Length; i++, k--)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
if (char.IsSurrogate(input[k]))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               reverse[i 
+ 1= input[k--];
InBlock.gif               reverse[i
++= input[k];
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               reverse[i] 
= input[k];
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif         }

InBlock.gif         
return new System.String(reverse);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Converts a string to sentence case.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to convert.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string SentenceCase(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
if (input.Length < 1)
InBlock.gif            
return input;
InBlock.gif
InBlock.gif         
string sentence = input.ToLower();
InBlock.gif         
return sentence[0].ToString().ToUpper() + 
InBlock.gif            sentence.Substring(
1);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Converts all spaces to HTML non-breaking spaces
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to convert.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string</returns>

InBlock.gif      public static string SpaceToNbsp(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
string space = "&nbsp;";
InBlock.gif         
return input.Replace(" ", space);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes all HTML tags from the passed string
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string whose 
InBlock.gif      
/// values should be replaced.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string StripTags(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         Regex stripTags 
= new Regex("<(.|\n)+?>");
InBlock.gif         
return stripTags.Replace(input, "");
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Converts a string to title case.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to convert.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string TitleCase(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return TitleCase(input, true);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Converts a string to title case.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to convert.</param>
InBlock.gif      
/// <param name="ignoreShortWords">If true, 
InBlock.gif      
/// does not capitalize words like
InBlock.gif      
/// "a", "is", "the", etc.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string TitleCase(string input, 
InBlock.gif         
bool ignoreShortWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         List
<string> ignoreWords = null;
InBlock.gif         
if (ignoreShortWords)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
//TODO: Add more ignore words?
InBlock.gif
            ignoreWords = new List<string>();
InBlock.gif            ignoreWords.Add(
"a");
InBlock.gif            ignoreWords.Add(
"is");
InBlock.gif            ignoreWords.Add(
"was");
InBlock.gif            ignoreWords.Add(
"the");
ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
string[] tokens = input.Split(' ');
InBlock.gif         StringBuilder sb 
= new StringBuilder(input.Length);
InBlock.gif         
foreach (string s in tokens)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
if (ignoreShortWords == true
InBlock.gif                
&& s != tokens[0]
InBlock.gif                
&& ignoreWords.Contains(s.ToLower()))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               sb.Append(s 
+ " ");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               sb.Append(s[
0].ToString().ToUpper());
InBlock.gif               sb.Append(s.Substring(
1).ToLower());
InBlock.gif               sb.Append(
" ");
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif         }

InBlock.gif
InBlock.gif         
return sb.ToString().Trim();
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Removes multiple spaces between words
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to trim.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string TrimIntraWords(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         Regex regEx 
= new Regex(@"[\s]+");
InBlock.gif         
return regEx.Replace(input, " ");
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Converts new line(\n) and carriage return(\r) symbols to
InBlock.gif      
/// HTML line breaks.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to convert.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string NewLineToBreak(string input)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         Regex regEx 
= new Regex(@"[\n|\r]+");
InBlock.gif         
return regEx.Replace(input, "<br />");
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Wraps the passed string at the 
InBlock.gif      
/// at the next whitespace on or after the 
InBlock.gif      
/// total charCount has been reached
InBlock.gif      
/// for that line.  Uses the environment new line
InBlock.gif      
/// symbol for the break text.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to wrap.</param>
InBlock.gif      
/// <param name="charCount">The number of characters 
InBlock.gif      
/// per line.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string WordWrap(string input, int charCount)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.WordWrap(input, charCount, 
InBlock.gif            
false, Environment.NewLine);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Wraps the passed string at the total 
InBlock.gif      
/// number of characters (if cuttOff is true)
InBlock.gif      
/// or at the next whitespace (if cutOff is false).
InBlock.gif      
/// Uses the environment new line
InBlock.gif      
/// symbol for the break text.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to wrap.</param>
InBlock.gif      
/// <param name="charCount">The number of characters 
InBlock.gif      
/// per line.</param>
InBlock.gif      
/// <param name="cutOff">If true, will break in 
InBlock.gif      
/// the middle of a word.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string WordWrap(string input, 
InBlock.gif         
int charCount, bool cutOff)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         
return StringHelper.WordWrap(input, charCount, 
InBlock.gif            cutOff, Environment.NewLine);
ExpandedSubBlockEnd.gif      }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif      
/**//// <summary>
InBlock.gif      
/// Wraps the passed string at the total number 
InBlock.gif      
/// of characters (if cuttOff is true)
InBlock.gif      
/// or at the next whitespace (if cutOff is false).
InBlock.gif      
/// Uses the passed breakText
InBlock.gif      
/// for lineBreaks.
InBlock.gif      
/// </summary>
InBlock.gif      
/// <param name="input">The string to wrap.</param>
InBlock.gif      
/// <param name="charCount">The number of 
InBlock.gif      
/// characters per line.</param>
InBlock.gif      
/// <param name="cutOff">If true, will break in 
InBlock.gif      
/// the middle of a word.</param>
InBlock.gif      
/// <param name="breakText">The line break text to use.</param>
ExpandedSubBlockEnd.gif      
/// <returns>A string.</returns>

InBlock.gif      public static string WordWrap(string input, int charCount,
InBlock.gif         
bool cutOff, string breakText)
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         StringBuilder sb 
= new StringBuilder(input.Length + 100);
InBlock.gif         
int counter = 0;
InBlock.gif
InBlock.gif         
if (cutOff)
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
while (counter < input.Length)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               
if (input.Length > counter + charCount)
ExpandedSubBlockStart.gifContractedSubBlock.gif               
dot.gif{
InBlock.gif                  sb.Append(input.Substring(counter, charCount));
InBlock.gif                  sb.Append(breakText);
ExpandedSubBlockEnd.gif               }

InBlock.gif               
else
ExpandedSubBlockStart.gifContractedSubBlock.gif               
dot.gif{
InBlock.gif                  sb.Append(input.Substring(counter));
ExpandedSubBlockEnd.gif               }

InBlock.gif               counter 
+= charCount;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif         }

InBlock.gif         
else
ExpandedSubBlockStart.gifContractedSubBlock.gif         
dot.gif{
InBlock.gif            
string[] strings = input.Split(' ');
InBlock.gif            
for (int i = 0; i < strings.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif               
// added one to represent the space.
InBlock.gif
               counter += strings[i].Length + 1
InBlock.gif               
if (i != 0 && counter > charCount)
ExpandedSubBlockStart.gifContractedSubBlock.gif               
dot.gif{
InBlock.gif                  sb.Append(breakText);
InBlock.gif                  counter 
= 0;
ExpandedSubBlockEnd.gif               }

InBlock.gif
InBlock.gif               sb.Append(strings[i] 
+ ' ');
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif         }

InBlock.gif         
// to get rid of the extra space at the end.
InBlock.gif
         return sb.ToString().TrimEnd(); 
ExpandedSubBlockEnd.gif      }

ExpandedSubBlockEnd.gif   }

ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/Titans/archive/2006/09/25/514017.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值