`
pcajax
  • 浏览: 2173718 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

StringHelp 类,常用字符串操作

阅读更多

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

namespace Jiaen.Components.Utility
{
   /// <summary>
   /// Helper functions for String not already found in C#.
   /// Inspired by PHP String Functions that are missing in .Net.
   /// </summary>
   public static class StringHelper
   {
      /// <summary>
      /// Base64 encodes a string.
      /// </summary>
      /// <param name="input">A string</param>
      /// <returns>A base64 encoded string</returns>
      public static string Base64StringEncode(string input)
      {
         byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(input);
         return Convert.ToBase64String(encbuff);
      }

      /// <summary>
      /// Base64 decodes a string.
      /// </summary>
      /// <param name="input">A base64 encoded string</param>
      /// <returns>A decoded string</returns>
      public static string Base64StringDecode(string input)
      {
         byte[] decbuff = Convert.FromBase64String(input);
         return System.Text.Encoding.UTF8.GetString(decbuff);
      }

      /// <summary>
      /// A case insenstive replace function.
      /// </summary>
      /// <param name="input">The string to examine.</param>
      /// <param name="newValue">The value to replace.</param>
      /// <param name="oldValue">The new value to be inserted</param>
      /// <returns>A string</returns>
      public static string CaseInsenstiveReplace(string input, string newValue, string oldValue)
      {
         Regex regEx = new Regex(oldValue, RegexOptions.IgnoreCase | RegexOptions.Multiline);
         return regEx.Replace(input, newValue);
      }

      /// <summary>
      /// Removes all the words passed in the filter words parameters. The replace is NOT case
      /// sensitive.
      /// </summary>
      /// <param name="input">The string to search.</param>
      /// <param name="filterWords">The words to repace in the input string.</param>
      /// <returns>A string.</returns>
      public static string FilterWords(string input, params string[] filterWords)
      {
         return StringHelper.FilterWords(input, char.MinValue, filterWords);
      }

      /// <summary>
      /// Removes all the words passed in the filter words parameters. The replace is NOT case
      /// sensitive.
      /// </summary>
      /// <param name="input">The string to search.</param>
      /// <param name="mask">A character that is inserted for each letter of the replaced word.</param>
      /// <param name="filterWords">The words to repace in the input string.</param>
      /// <returns>A string.</returns>
      public static string FilterWords(string input, char mask, params string[] filterWords)
      {
         string stringMask = mask == char.MinValue ? string.Empty : mask.ToString();
         string totalMask = stringMask;

         foreach (string s in filterWords)
         {
            Regex regEx = new Regex(s, RegexOptions.IgnoreCase | RegexOptions.Multiline);

            if (stringMask.Length > 0)
            {
               for (int i = 1; i < s.Length; i++)
                  totalMask += stringMask;
            }

            input = regEx.Replace(input, totalMask);

            totalMask = stringMask;
         }

         return input;
      }

      /// <summary>
      /// Checks the passed string to see if has any of the passed words. Not case-sensitive.
      /// </summary>
      /// <param name="input">The string to check.</param>
      /// <param name="hasWords">The words to check for.</param>
      /// <returns>A collection of the matched words.</returns>
      public static MatchCollection HasWords(string input, params string[] hasWords)
      {
         StringBuilder sb = new StringBuilder(hasWords.Length + 50);
         //sb.Append("[");

         foreach (string s in hasWords)
         {
            sb.AppendFormat("({0})|", StringHelper.HtmlSpecialEntitiesEncode(s.Trim()));
         }

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

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

      /// <summary>
      /// A wrapper around HttpUtility.HtmlEncode
      /// </summary>
      /// <param name="input">The string to be encoded</param>
      /// <returns>An encoded string</returns>
      public static string HtmlSpecialEntitiesEncode(string input)
      {
         return HttpUtility.HtmlEncode(input);
      }

      /// <summary>
      /// A wrapper around HttpUtility.HtmlDecode
      /// </summary>
      /// <param name="input">The string to be decoded</param>
      /// <returns>The decode string</returns>
      public static string HtmlSpecialEntitiesDecode(string input)
      {
         return HttpUtility.HtmlDecode(input);
      }

      /// <summary>
      /// MD5 encodes the passed string
      /// </summary>
      /// <param name="input">The string to encode.</param>
      /// <returns>An encoded string.</returns>
      public static string MD5String(string input)
      {
         // Create a new instance of the MD5CryptoServiceProvider object.
         MD5 md5Hasher = MD5.Create();

         // Convert the input string to a byte array and compute the hash.
         byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

         // Create a new Stringbuilder to collect the bytes
         // and create a string.
         StringBuilder sBuilder = new StringBuilder();

         // Loop through each byte of the hashed data
         // and format each one as a hexadecimal string.
         for (int i = 0; i < data.Length; i++)
         {
            sBuilder.Append(data[i].ToString("x2"));
         }

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

      /// <summary>
      /// Verified a string against the passed MD5 hash.
      /// </summary>
      /// <param name="input">The string to compare.</param>
      /// <param name="hash">The hash to compare against.</param>
      /// <returns>True if the input and the hash are the same, false otherwise.</returns>
      public static bool MD5VerifyString(string input, string hash)
      {
         // Hash the input.
         string hashOfInput = StringHelper.MD5String(input);

         // Create a StringComparer an comare the hashes.
         StringComparer comparer = StringComparer.OrdinalIgnoreCase;

         if (0 == comparer.Compare(hashOfInput, hash))
         {
            return true;
         }
         else
         {
            return false;
         }
      }

      /// <summary>
      /// Left pads the passed input using the HTML non-breaking string entity (&nbsp;)
      /// for the total number of spaces.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadLeftHtmlSpaces(string input, int totalSpaces)
      {
         string space = "&nbsp;";
         return PadLeft(input, space, totalSpaces * space.Length);
      }

      /// <summary>
      /// Left pads the passed input 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.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="pad">The string to uses as padding.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadLeft(string input, string pad, int totalWidth)
      {
         return StringHelper.PadLeft(input, pad, totalWidth, false);
      }

      /// <summary>
      /// Left pads the passed input using the passed pad string
      /// for the total number of spaces.  It will cut-off the pad so that 
      /// the string does not exceed the total width.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="pad">The string to uses as padding.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadLeft(string input, string pad, int totalWidth, bool cutOff)
      {
         if (input.Length >= totalWidth)
            return input;

         int padCount = pad.Length;
         string paddedString = input;

         while (paddedString.Length < totalWidth)
         {
            paddedString += pad;
         }

         // trim the excess.
         if (cutOff)
            paddedString = paddedString.Substring(0, totalWidth);

         return paddedString;
      }

      /// <summary>
      /// Right pads the passed input using the HTML non-breaking string entity (&nbsp;)
      /// for the total number of spaces.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadRightHtmlSpaces(string input, int totalSpaces)
      {
         string space = "&nbsp;";
         return PadRight(input, space, totalSpaces * space.Length);
      }

      /// <summary>
      /// Right pads the passed input 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.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="pad">The string to uses as padding.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadRight(string input, string pad, int totalWidth)
      {
         return StringHelper.PadRight(input, pad, totalWidth, false);
      }

      /// <summary>
      /// Right pads the passed input using the passed pad string
      /// for the total number of spaces.  It will cut-off the pad so that 
      /// the string does not exceed the total width.
      /// </summary>
      /// <param name="input">The string to pad.</param>
      /// <param name="pad">The string to uses as padding.</param>
      /// <param name="totalSpaces">The total number to pad the string.</param>
      /// <returns>A padded string.</returns>
      public static string PadRight(string input, string pad, int totalWidth, bool cutOff)
      {
         if (input.Length >= totalWidth)
            return input;

         string paddedString = string.Empty;

         while (paddedString.Length < totalWidth - input.Length)
         {
            paddedString += pad;
         }

         // trim the excess.
         if (cutOff)
            paddedString = paddedString.Substring(0, totalWidth - input.Length);

         paddedString += input;

         return paddedString;
      }

      /// <summary>
      /// Removes the new line (\n) and carriage return (\r) symbols.
      /// </summary>
      /// <param name="input">The string to search.</param>
      /// <returns>A string</returns>
      public static string RemoveNewLines(string input)
      {
         return StringHelper.RemoveNewLines(input, false);
      }

      /// <summary>
      /// Removes the new line (\n) and carriage return (\r) symbols.
      /// </summary>
      /// <param name="input">The string to search.</param>
      /// <param name="addSpace">If true, adds a space (" ") for each newline and carriage
      /// return found.</param>
      /// <returns>A string</returns>
      public static string RemoveNewLines(string input, bool addSpace)
      {
         string replace = string.Empty;
         if (addSpace)
            replace = " ";

         string pattern = @"[\r|\n]";
         Regex regEx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);

         return regEx.Replace(input, replace);
      }

      /// <summary>
      /// Reverse a string.
      /// </summary>
      /// <param name="input">The string to reverse</param>
      /// <returns>A string</returns>
      public static string Reverse(string input)
      {
         if (input.Length <= 1)
            return input;

         char[] c = input.ToCharArray();
         StringBuilder sb = new StringBuilder(c.Length);
         for (int i = c.Length - 1; i > -1; i--)
            sb.Append(c[i]);

         return sb.ToString();
      }

      /// <summary>
      /// Converts a string to sentence case.
      /// </summary>
      /// <param name="input">The string to convert.</param>
      /// <returns>A string</returns>
      public static string SentenceCase(string input)
      {
         if (input.Length < 1)
            return input;

         string sentence = input.ToLower();
         return sentence[0].ToString().ToUpper() + sentence.Substring(1);
      }

      /// <summary>
      /// Converts all spaces to HTML non-breaking spaces
      /// </summary>
      /// <param name="input">The string to convert.</param>
      /// <returns>A string</returns>
      public static string SpaceToNbsp(string input)
      {
         string space = "&nbsp;";
         return input.Replace(" ", space);
      }

      /// <summary>
      /// Removes all HTML tags from the passed string
      /// </summary>
      /// <param name="input">The string whose values should be replaced.</param>
      /// <returns>A string.</returns>
      public static string StripTags(string input)
      {
         Regex stripTags = new Regex("<(.|\n)+?>");
         return stripTags.Replace(input, "");
      }

      /// <summary>
      /// Converts a string to title case.
      /// </summary>
      /// <param name="input">The string to convert.</param>
      /// <returns>A string.</returns>
      public static string TitleCase(string input)
      {
         return TitleCase(input, true);
      }

      /// <summary>
      /// Converts a string to title case.
      /// </summary>
      /// <param name="input">The string to convert.</param>
      /// <param name="ignoreShortWords">If true, does not capitalize words like
      /// "a", "is", "the", etc.</param>
      /// <returns>A string.</returns>
      public static string TitleCase(string input, bool ignoreShortWords)
      {
         List<string> ignoreWords = null;
         if (ignoreShortWords)
         {
            //TODO: Add more ignore words?
            ignoreWords = new List<string>();
            ignoreWords.Add("a");
            ignoreWords.Add("is");
            ignoreWords.Add("was");
            ignoreWords.Add("the");
         }

         string[] tokens = input.Split(' ');
         StringBuilder sb = new StringBuilder(input.Length);
         foreach (string s in tokens)
         {
            if (ignoreShortWords == true
                && s != tokens[0]
                && ignoreWords.Contains(s.ToLower()))
            {
               sb.Append(s + " ");
            }
            else
            {
               sb.Append(s[0].ToString().ToUpper());
               sb.Append(s.Substring(1).ToLower());
               sb.Append(" ");
            }
         }

         return sb.ToString().Trim();
      }

      /// <summary>
      /// Removes multiple spaces between words
      /// </summary>
      /// <param name="input">The string to trim.</param>
      /// <returns>A string.</returns>
      public static string TrimIntraWords(string input)
      {
         Regex regEx = new Regex(@"[\s]+");
         return regEx.Replace(input, " ");
      }

      /// <summary>
      /// Converts new line(\n) and carriage return(\r) symbols to
      /// HTML line breaks.
      /// </summary>
      /// <param name="input">The string to convert.</param>
      /// <returns>A string.</returns>
      public static string NewLineToBreak(string input)
      {
         Regex regEx = new Regex(@"[\n|\r]+");
         return regEx.Replace(input, "<br />");
      }

      /// <summary>
      /// Wraps the passed string up the
      /// until the next whitespace on or after the total charCount has been reached
      /// for that line.  Uses the environment new line
      /// symbol for the break text.
      /// </summary>
      /// <param name="input">The string to wrap.</param>
      /// <param name="charCount">The number of characters per line.</param>
      /// <returns>A string.</returns>
      public static string WordWrap(string input, int charCount)
      {
         return StringHelper.WordWrap(input, charCount, false, Environment.NewLine);
      }

      /// <summary>
      /// Wraps the passed string up the total number of characters (if cuttOff is true)
      /// or until the next whitespace (if cutOff is false).  Uses the environment new line
      /// symbol for the break text.
      /// </summary>
      /// <param name="input">The string to wrap.</param>
      /// <param name="charCount">The number of characters per line.</param>
      /// <param name="cutOff">If true, will break in the middle of a word.</param>
      /// <returns>A string.</returns>
      public static string WordWrap(string input, int charCount, bool cutOff)
      {
         return StringHelper.WordWrap(input, charCount, cutOff, Environment.NewLine);
      }

      /// <summary>
      /// Wraps the passed string up the total number of characters (if cuttOff is true)
      /// or until the next whitespace (if cutOff is false).  Uses the passed breakText
      /// for lineBreaks.
      /// </summary>
      /// <param name="input">The string to wrap.</param>
      /// <param name="charCount">The number of characters per line.</param>
      /// <param name="cutOff">If true, will break in the middle of a word.</param>
      /// <param name="breakText">The line break text to use.</param>
      /// <returns>A string.</returns>
      public static string WordWrap(string input, int charCount, bool cutOff,
          string breakText)
      {
         StringBuilder sb = new StringBuilder(input.Length + 100);
         int counter = 0;

         if (cutOff)
         {
            while (counter < input.Length)
            {
               if (input.Length > counter + charCount)
               {
                  sb.Append(input.Substring(counter, charCount));
                  sb.Append(breakText);
               }
               else
               {
                  sb.Append(input.Substring(counter));
               }
               counter += charCount;
            }
         }
         else
         {
            string[] strings = input.Split(' ');
            for (int i = 0; i < strings.Length; i++)
            {
               counter += strings[i].Length + 1; // the added one is to represent the inclusion of the space.
               if (i != 0 && counter > charCount)
               {
                  sb.Append(breakText);
                  counter = 0;
               }

               sb.Append(strings[i] + ' ');
            }
         }
         return sb.ToString().TrimEnd(); // to get rid of the extra space at the end.
      }

      /// <summary>
      /// 处理null值
      /// </summary>
      /// <param name="text"></param>
      /// <returns></returns>
      public static string convertStr(string text)
      {
          if (text == null)
          {
              text = "";
          }
          return text.Trim();
      }

      /// <summary>
      /// 处理长度值
      /// </summary>
      /// <param name="text"></param>
      /// <returns></returns>
      public static string subStr(int length,string text)
      {
          if (text.Length >= length)
          {
              text = text.Substring(0,length)+" ...";
          }
          return text;
      }
   }
}

分享到:
评论

相关推荐

    常用字符串操作的实现方式

    这些是Java中常用的字符串操作,它们在日常开发中扮演着至关重要的角色,无论是数据处理还是用户界面的显示,都能见到它们的身影。了解并熟练掌握这些操作,能够帮助开发者更高效地处理字符串相关的任务。

    ABAP常用字符串操作收集整理

    ABAP 中的字符串操作是开发者日常工作中不可或缺的一部分,本文将对 ABAP 中常用的字符串操作进行收集和整理,包括字符串连接、字符串分隔、字符串查找、字符串替换、去前导 0 等操作。 1. 字符串连接 CONCATENATE...

    java 字符串工具类 java 字符串工具类

    java 字符串工具类 java 字符串工具类java 字符串工具类 java 字符串工具类java 字符串工具类 java 字符串工具类java 字符串工具类 java 字符串工具类java 字符串工具类 java 字符串工具类java 字符串工具类 java ...

    pb函数库之字符串操作函数

    下面是pb函数库中的一些常用字符串操作函数: 1. Fill()函数:Fill()函数可以建立一个由指定字符串填充的指定长度的字符串。其语法为Fill(chars, n),其中chars是指定用于重复填充的字符串,n是指定由该函数返回的...

    C#实现实体类与字符串互相转换的方法

    本文实例讲述了C#实现实体类与字符串互相转换的方法。分享给大家供大家参考。具体实现方法如下: using System; using System.Collections.Generic; using System.Text; namespace PackDLL.Data.ConvertData { ///...

    常用oracle字符串操作函数

    本文将深入探讨Oracle中的常用字符串操作函数,帮助你更好地理解和运用这些功能。 1. **LENGTH()** 函数: 这个函数用于返回字符串的长度,不包括结束的空字符。例如,`LENGTH('Hello')` 将返回5。 2. **SUBSTR()...

    字符串操作封装函数

    标题中的"字符串操作封装函数"指的是将常用的字符串处理功能封装成独立的函数,以便于在代码中重复使用,提高代码的复用性和可读性。这样的做法遵循了软件工程中的模块化原则,能够减少代码冗余,提升开发效率。 ...

    C#字符串操作

    以下是一些常用的字符串属性和方法: 1. `Length`:返回字符串中字符的数量。 2. `Substring(int startIndex, int length)`:返回一个新的字符串,它是原字符串的一部分,从startIndex位置开始,长度为length。 3. ...

    java 字符串操作类

    `StringUtil` 类是这样一个工具类,它集合了多种常用的字符串处理方法,以提高开发效率并减少代码重复。在这个类中,我们可以找到包括分隔、插入、判断字符串状态(空或非空)、去除空格等多种功能,这些都是在实际...

    一个C语言常用字符串操作函数库.zip

    本压缩包"一个C语言常用字符串操作函数库.zip"中可能包含了一系列常用的C语言字符串处理函数的实现,这些函数可以帮助我们更高效、方便地进行字符串的创建、修改、比较和查找等操作。下面将详细解释一些常见的C语言...

    字符串工具类

    字符串工具类,格式字符串、随机数生成、ip区间判断!

    Objective-C中字符串操作总结

    以下是Objective-C中字符串操作的详细总结,包含常用的方法和概念。 ### 不可变字符串NSString 1. **声明和初始化**: 使用`@”Hello”`这样的字面量方式是声明并初始化NSString对象的简便方法。 2. **字符串...

    PB程序中常用的字符串替换函数

    下面我们就基于题目中的信息,详细探讨一下如何在PB程序中实现一个常用的字符串替换函数。 ### PB程序中常用的字符串替换函数 #### 背景介绍 PowerBuilder是一种广泛应用于企业级应用开发的快速应用开发工具。尽管...

    VB拆分字符串,分隔字符串

    `Split`函数是最常用的字符串拆分方法。它接受一个字符串作为输入,并根据指定的分隔符返回一个字符串数组。基本语法如下: ```vb Dim result() As String result = Split(inputString, delimiter) ``` 在这里,`...

    常用CS类库(字符串操作类,数据库操作类,邮件发送类,正则类,对象转换类,文件操作类,常用JS操作类,Office操作类等等)

    1. **字符串操作类**:这类库提供了丰富的字符串处理方法,包括拼接、分割、查找、替换、格式化等。例如,.NET Framework中的`System.Text.StringBuilder`类用于高效地构建和修改字符串,避免了多次创建字符串导致的...

    [字符串]字符串提取(获取两个字符串中间的字符串)

    标题中的“字符串提取(获取两个字符串中间的字符串)”就是指的这个操作。 首先,C#提供了丰富的字符串类(System.String)和正则表达式类(System.Text.RegularExpressions)来帮助我们完成这项工作。在标准的字符...

    工具类_字符串处理

    例如,Java中的`java.util.StringBuilder`和`java.util.StringBuffer`就是两个常用的字符串操作工具类,它们提供了字符串拼接、替换、查找等多种功能,并且在多线程环境下,`StringBuffer`比`StringBuilder`更安全,...

    python字符串学习笔记.python字符串操作方法.doc

    Python字符串是编程中常用的数据类型,用于存储和处理文本信息。在Python中,字符串是由一个或多个字符组成的序列,它们可以被单引号(' ')或双引号(" ")包围。以下是一些关于Python字符串的重要知识点: 1. **字符...

Global site tag (gtag.js) - Google Analytics