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的常用函数的用法和它与字符数组的区别与联系 限制条件或者存在 ...
随机推荐
- Mocha+should+Karma自动化测试教程
Mocha+should+Karma自动化测试教程 一.了解TDD与BDD 首先,为什么我们了解TDD与BDD的是什么意思? 在实际项目中,大部分都是采用BDD的形式进行开发,也就是行为驱动开发. T ...
- SpringBoot使用Nacos配置中心
本文介绍SpringBoot如何使用阿里巴巴Nacos做配置中心. 1.Nacos简介 Nacos是阿里巴巴集团开源的一个易于使用的平台,专为动态服务发现,配置和服务管理而设计.它可以帮助您轻松构建云 ...
- 大数据集群ssh登录其他机器失败 RSA host key for zb03 has changed and you have requested strict checking. Host key verification failed.
[hadoop@zb02 .ssh]$ scp authorized_keys hadoop@zb03:/home/hadoop/.ssh @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...
- selenium3 TestNG 介绍与配置
一.TestNG介绍 我之前有学习过Junit,Nunit 这些工具,现在想看看TestNG,那么TestNG是什么呢?他们之间有什么区别呢? TestNG(Next Generation)是一个测试 ...
- python获取文件所在目录
1.执行的python程序获取自己文件所在目录 import os,sys os.chdir(sys.path[0]); dir_name = os.path.abspath(os.path.join ...
- linux下fcitx的安装与配置
首先安装fcitx pacman -S fcitx-im fcitx-config fcitx-cloudpinyin 之后进行配置 nano ~/.xprofile 写入 export XIM=fc ...
- maven打包忽略静态资源解决办法,dispatchServlet拦截静态资源请求的解决办法
问题: maven 打包时,有的文件打不进去target 解决: 因为maven打包默认打Java文件.在项目中的pom文件中加build标签 <build> <resources& ...
- .net不同集合类型及使用场合
1.Dictionary-相当于字典[可以通过过索引(hash值)速添加.删除.查找]:如果需要非常快地添加.删除和查找项目,而且不关心集合中项目的顺序,那么首先应该考虑使用 System.Colle ...
- 学习ActiveMQ(八):activemq消息的持久化
1. 持久化方式介绍前面我们也简单提到了activemq提供的插件式的消息存储,在这里再提一下,主要有以下几种方式: AMQ消息存储-基于文件的存储方式,是activemq开始的版本默认的消息存储方式 ...
- vue 基础的一些字眼及路由
每个框架都有一些自己的写法和一些字眼 摘自 vue 官网 v-bind 缩写 <!-- 完整语法 --> <a v-bind:href="url">...& ...