C# string 常用功能的方法扩展
#region Usings
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using DragonUtility.DataTypes.Formatters;
using Microsoft.VisualBasic;
#endregion namespace DragonUtility.DataTypes.ExtensionMethods
{
/// <summary>
/// String extensions
/// </summary>
public static class StringExtensions
{
#region Functions #region Encode /// <summary>
/// 编码转换,把字符串从一种编码转换到另一种编码
/// </summary>
/// <param name="Input">input string</param>
/// <param name="OriginalEncodingUsing">The type of encoding the string is currently using (defaults to ASCII)</param>
/// <param name="EncodingUsing">The type of encoding the string is converted into (defaults to UTF8)</param>
/// <returns>string of the byte array</returns>
public static string Encode(this string Input, Encoding OriginalEncodingUsing = null, Encoding EncodingUsing = null)
{
if (string.IsNullOrEmpty(Input))
return "";
OriginalEncodingUsing = OriginalEncodingUsing.NullCheck(new ASCIIEncoding());
EncodingUsing = EncodingUsing.NullCheck(new UTF8Encoding());
return Encoding.Convert(OriginalEncodingUsing, EncodingUsing, Input.ToByteArray(OriginalEncodingUsing))
.ToEncodedString(EncodingUsing); }
#endregion #region FromBase64 /// <summary>
/// Converts base 64 string based on the encoding passed in
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="EncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
/// <returns>string in the encoding format</returns>
public static string FromBase64(this string Input, Encoding EncodingUsing)
{
if (string.IsNullOrEmpty(Input))
return "";
byte[] TempArray = Convert.FromBase64String(Input);
return EncodingUsing.NullCheck(new UTF8Encoding()).GetString(TempArray);
} /// <summary>
/// Converts base 64 string to a byte array
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>A byte array equivalent of the base 64 string</returns>
public static byte[] FromBase64(this string Input)
{
return string.IsNullOrEmpty(Input) ? new byte[] : Convert.FromBase64String(Input);
} #endregion #region Left /// <summary>
/// Gets the first x number of characters from the left hand side
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="Length">x number of characters to return</param>
/// <returns>The resulting string</returns>
public static string Left(this string Input, int Length)
{
return string.IsNullOrEmpty(Input) ? "" : Input.Substring(, Input.Length > Length ? Length : Input.Length);
} #endregion #region Right /// <summary>
/// Gets the last x number of characters from the right hand side
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="Length">x number of characters to return</param>
/// <returns>The resulting string</returns>
public static string Right(this string Input, int Length)
{
if (string.IsNullOrEmpty(Input))
return "";
Length = Input.Length > Length ? Length : Input.Length;
return Input.Substring(Input.Length - Length, Length);
} #endregion #region ToBase64 /// <summary>
/// Converts from the specified encoding to a base 64 string
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="OriginalEncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
/// <returns>Bas64 string</returns>
public static string ToBase64(this string Input, Encoding OriginalEncodingUsing = null)
{
if (string.IsNullOrEmpty(Input))
return "";
byte[] TempArray = OriginalEncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
return Convert.ToBase64String(TempArray);
} #endregion #region ToByteArray /// <summary>
/// Converts a string to a byte array
/// </summary>
/// <param name="Input">input string</param>
/// <param name="EncodingUsing">The type of encoding the string is using (defaults to UTF8)</param>
/// <returns>the byte array representing the string</returns>
public static byte[] ToByteArray(this string Input, Encoding EncodingUsing = null)
{
return string.IsNullOrEmpty(Input) ? null : EncodingUsing.NullCheck(new UTF8Encoding()).GetBytes(Input);
} #endregion #region ToFirstCharacterUpperCase /// <summary>
/// Takes the first character of an input string and makes it uppercase
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>String with the first character capitalized</returns>
public static string ToFirstCharacterUpperCase(this string Input)
{
if (string.IsNullOrEmpty(Input))
return "";
char[] InputChars = Input.ToCharArray();
for (int x = ; x < InputChars.Length; ++x)
{
if (InputChars[x] != ' ' && InputChars[x] != '\t')
{
InputChars[x] = char.ToUpper(InputChars[x]);
break;
}
}
return new string(InputChars);
} #endregion #region ToSentenceCapitalize /// <summary>
/// Capitalizes each sentence within the string
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>String with each sentence capitalized</returns>
public static string ToSentenceCapitalize(this string Input)
{
if (string.IsNullOrEmpty(Input))
return "";
string[] Seperator = { ".", "?", "!" };
string[] InputStrings = Input.Split(Seperator, StringSplitOptions.None);
for (int x = ; x < InputStrings.Length; ++x)
{
if (!string.IsNullOrEmpty(InputStrings[x]))
{
Regex TempRegex = new Regex(InputStrings[x]);
InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
Input = TempRegex.Replace(Input, InputStrings[x]);
}
}
return Input;
} #endregion #region ToTitleCase /// <summary>
/// Capitalizes the first character of each word
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>String with each word capitalized</returns>
public static string ToTitleCase(this string Input)
{
if (string.IsNullOrEmpty(Input))
return "";
string[] Seperator = { " ", ".", "\t", System.Environment.NewLine, "!", "?" };
string[] InputStrings = Input.Split(Seperator, StringSplitOptions.None);
for (int x = ; x < InputStrings.Length; ++x)
{
if (!string.IsNullOrEmpty(InputStrings[x])
&& InputStrings[x].Length > )
{
Regex TempRegex = new Regex(InputStrings[x]);
InputStrings[x] = InputStrings[x].ToFirstCharacterUpperCase();
Input = TempRegex.Replace(Input, InputStrings[x]);
}
}
return Input;
} #endregion #region NumberTimesOccurs /// <summary>
/// returns the number of times a string occurs within the text
/// </summary>
/// <param name="Input">input text</param>
/// <param name="Match">The string to match (can be regex)</param>
/// <returns>The number of times the string occurs</returns>
public static int NumberTimesOccurs(this string Input, string Match)
{
return string.IsNullOrEmpty(Input) ? : new Regex(Match).Matches(Input).Count;
} #endregion #region Reverse /// <summary>
/// Reverses a string
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>The reverse of the input string</returns>
public static string Reverse(this string Input)
{
return new string(Input.Reverse<char>().ToArray());
} #endregion #region FilterOutText /// <summary>
/// Removes the filter text from the input.
/// </summary>
/// <param name="Input">Input text</param>
/// <param name="Filter">Regex expression of text to filter out</param>
/// <returns>The input text minus the filter text.</returns>
public static string FilterOutText(this string Input, string Filter)
{
if (string.IsNullOrEmpty(Input))
return "";
return string.IsNullOrEmpty(Filter) ? Input : new Regex(Filter).Replace(Input, "");
} #endregion #region KeepFilterText /// <summary>
/// Removes everything that is not in the filter text from the input.
/// </summary>
/// <param name="Input">Input text</param>
/// <param name="Filter">Regex expression of text to keep</param>
/// <returns>The input text minus everything not in the filter text.</returns>
public static string KeepFilterText(this string Input, string Filter)
{
if (string.IsNullOrEmpty(Input) || string.IsNullOrEmpty(Filter))
return "";
Regex TempRegex = new Regex(Filter);
MatchCollection Collection = TempRegex.Matches(Input);
StringBuilder Builder = new StringBuilder();
foreach (Match Match in Collection)
Builder.Append(Match.Value);
return Builder.ToString();
} #endregion #region AlphaNumericOnly /// <summary>
/// Keeps only alphanumeric characters
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>the string only containing alphanumeric characters</returns>
public static string AlphaNumericOnly(this string Input)
{
return Input.KeepFilterText("[a-zA-Z0-9]");
} #endregion #region AlphaCharactersOnly /// <summary>
/// Keeps only alpha characters
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>the string only containing alpha characters</returns>
public static string AlphaCharactersOnly(this string Input)
{
return Input.KeepFilterText("[a-zA-Z]");
} #endregion #region NumericOnly /// <summary>
/// Keeps only numeric characters
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="KeepNumericPunctuation">Determines if decimal places should be kept</param>
/// <returns>the string only containing numeric characters</returns>
public static string NumericOnly(this string Input, bool KeepNumericPunctuation = true)
{
return KeepNumericPunctuation ? Input.KeepFilterText(@"[0-9\.]") : Input.KeepFilterText("[0-9]");
} #endregion #region IsUnicode /// <summary>
/// Determines if a string is unicode
/// </summary>
/// <param name="Input">Input string</param>
/// <returns>True if it's unicode, false otherwise</returns>
public static bool IsUnicode(this string Input)
{
return string.IsNullOrEmpty(Input) ? true : Regex.Replace(Input, @"[^\u0000-\u007F]", "") != Input;
} #endregion #region FormatString /// <summary>
/// Formats a string based on a format string passed in:
/// # = digits
/// @ = alpha characters
/// \ = escape char
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="Format">Format of the output string</param>
/// <returns>The formatted string</returns>
public static string FormatString(this string Input, string Format)
{
return new GenericStringFormatter().Format(Input, Format);
} #endregion #region RegexFormat /// <summary>
/// Uses a regex to format the input string
/// </summary>
/// <param name="Input">Input string</param>
/// <param name="Format">Regex string used to</param>
/// <param name="OutputFormat">Output format</param>
/// <param name="Options">Regex options</param>
/// <returns>The input string formatted by using the regex string</returns>
public static string RegexFormat(this string Input, string Format, string OutputFormat, RegexOptions Options = RegexOptions.None)
{
Input.ThrowIfNullOrEmpty("Input");
return Regex.Replace(Input, Format, OutputFormat, Options);
} #endregion #region 转换
/// <summary>
/// 全角转半角
/// </summary>
/// <param name="input">要转换的字符串</param>
/// <returns>转换完的字符串</returns>
public static string Narrow(this string input)
{
return Strings.StrConv(input, VbStrConv.Narrow, );
}
/// <summary>
/// 半角转全角
/// </summary>
/// <param name="input">要转换的字符串</param>
/// <returns>转换完的字符串</returns>
public static string Wide(this string input)
{
return Strings.StrConv(input, VbStrConv.Wide, );
}
/// <summary>
/// 简体转繁体
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string TraditionalChinese(this string input)
{
return Strings.StrConv(input, VbStrConv.TraditionalChinese, );
}
/// <summary>
/// 繁体转简体
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string SimplifiedChinese(this string input)
{
return Strings.StrConv(input, VbStrConv.SimplifiedChinese, );
}
/// <summary>
/// 将每个单词首字母大写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ProperCase(this string input)
{
return Strings.StrConv(input, VbStrConv.ProperCase, );
}
#endregion #endregion
}
}
C# string 常用功能的方法扩展的更多相关文章
- Burpsuite神器常用功能使用方法总结
Burpsuite介绍: 一款可以进行再WEB应用程序的集成攻击测试平台. 常用的功能: 抓包.重放.爆破 1.使用Burp进行抓包 这边抓包,推荐360浏览器7.1版本(原因:方便) 在浏览器设置代 ...
- python3 os模块的常用功能及方法总结
1.os.getcwd() #显示当前工作路径 2.os.listdir('dirname') #返回指定目录下的所有文件和目录名 3.os.remove('filename') ...
- 第190天:js---String常用属性和方法(最全)
String常用属性和方法 一.string对象构造函数 /*string对象构造函数*/ console.log('字符串即对象');//字符串即对象 //传统方式 - 背后会自动将其转换成对象 / ...
- C#构造方法(函数) C#方法重载 C#字段和属性 MUI实现上拉加载和下拉刷新 SVN常用功能介绍(二) SVN常用功能介绍(一) ASP.NET常用内置对象之——Server sql server——子查询 C#接口 字符串的本质 AJAX原生JavaScript写法
C#构造方法(函数) 一.概括 1.通常创建一个对象的方法如图: 通过 Student tom = new Student(); 创建tom对象,这种创建实例的形式被称为构造方法. 简述:用来初 ...
- String对象方法扩展
/** *字符串-格式化 */ String.prototype.format = function(){ var args = arguments;//获取函数传递参数数组,以便在replace回调 ...
- Keil的使用方法 - 常用功能(二)
Ⅰ.概述 上一篇文章是总结关于Keil使用方法-常用功能(一),关于(文件和编译)工具栏每一个按钮的功能描述和快捷键的使用. 我将每一篇Keil使用方法的文章都汇总在一起,回顾前面的总结请点击下面的链 ...
- Keil的使用方法 - 常用功能(一)
Ⅰ.概述 学习一门软件的开发,开发工具的掌握可以说尤为重要.由于Keil集成开发工具支持多种MCU平台的开发,是市面上比较常见的,也是功能比较强大一款IDE.所以,对于大多数人说,选择Keil几乎是单 ...
- JavaScript之Number、String、Array常用属性与方法手册
Number isFinite函数 Number.isFinite() 方法用来检测传入的参数是否是一个有穷数(finite number). 语法: Number.isFinite(value) 例 ...
- string类的常用功能演示
这个程序可用随着我对string的用法的增多而有调整. /* 功能说明: string类的常用功能演示. 实现方式: 主要是演示string的常用函数的用法和它与字符数组的区别与联系 限制条件或者存在 ...
随机推荐
- 后端for循环补充
我们的for循环里面,在外面可以调用它最后一次循环的值,pycharm尽管会飘黄色,但是系统是可以识别出来的,能够调用,而且是循环最后一次的值
- 【java】-- java并发包总结
1.同步容器类 1.1.Vector与ArrayList异同 1.Arraylist和Vector都是采用数组方式存储数据,都允许直接序号索引元素,所以查找速度快,但是插入数据等操作涉及到数组元素移动 ...
- Material Design 常用控件
Material Design Material Design (原质化/材料化设计) 是在2014年Google I/O大会上推出的一套全新的界面设计语言. 意在解决Android平台界面风格不统一 ...
- 移除K位数字
1.题目来源:选自LeetCode 402: 2.问题描述: 3.问题分析 通过分析我们可以得出这样的结论:如果后一个数字比前面的数字小的话,那么我们就要把前面的一个数字删除掉,并且每次把字符串中拆出 ...
- node.js官方文档解析 01—assert 断言
assert-------断言 new assert.AssertionError(options) Error 的一个子类,表明断言的失败. options(选项)有下列对象 message < ...
- IOS开发中发布的时候取消日志打印
在PCH文件中定义如下宏 #if DEBUG #define NSLog(...) NSLog(__VA_ARGS__) #define debugMethod() NSLog(@"%s&q ...
- CentOS裸机环境下安装php-7.3.1
安装步骤如下 安装必要的软件 获取源码 编译安装 安装过程可能遇到的一些问题 编译参数详解 安装步骤如下 安装必要的软件 yum install -y autoconf automake libtoo ...
- 107个JS常用方法(持续更新中)
1.输出语句:document.write(""); 2.JS中的注释为//3.传统的HTML文档顺序是:document->html->(head,body)4.一个 ...
- LeetCode 240 - 搜索二维矩阵 II
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target.该矩阵具有以下特性: 每行的元素从左到右升序排列.每列的元素从上到下升序排列.示例: 现有矩阵 matrix 如 ...
- CentOS最基本的20个常用命令
1. man 对你熟悉或不熟悉的命令提供帮助解释eg:man ls 就可以查看ls相关的用法注:按q键或者ctrl+c退出,在linux下可以使用ctrl+c终止当前程序运行. 2. ls 查看目录或 ...