【终结版】C#常用函数和方法集汇总
C#里面的常用的函数和方法非常重要,然而做题的时候会经常忘记这些封装好的方法,所以我总结一下 C#常用函数和方法集。
【1】C#操作字符串的常用使用方法
在 C# 中,您可以使用字符数组来表示字符串,但是,更常见的做法是使用 string 关键字来声明一个字符串变量。string 关键字是 System.String 类的别名。
一.创建 String 对象
- 通过给 String 变量指定一个字符串
- 通过使用 String 类构造函数
- 通过使用字符串串联运算符( + )
- 通过检索属性或调用一个返回字符串的方法
- 通过格式化方法来转换一个值或对象为它的字符串表示形式
- using System;
- namespace StringApplication
- {
- class Program
- {
- static void Main(string[] args)
- {
- //字符串,字符串连接
- string fname, lname;
- fname = "Rowan";
- lname = "Atkinson";
- string fullname = fname + lname;
- Console.WriteLine("Full Name: {0}", fullname);
- //通过使用 string 构造函数
- char[] letters = { 'H', 'e', 'l', 'l','o' };
- string greetings = new string(letters);
- Console.WriteLine("Greetings: {0}", greetings);
- //方法返回字符串
- string[] sarray = { "Hello", "From", "Tutorials", "Point" };
- string message = String.Join(" ", sarray);
- Console.WriteLine("Message: {0}", message);
- //用于转化值的格式化方法
- DateTime waiting = new DateTime(, , , , , );
- string chat = String.Format("Message sent at {0:t} on {0:D}",
- waiting);
- Console.WriteLine("Message: {0}", chat);
- Console.ReadKey() ;
- }
- }
- }
结果为:
- Full Name: RowanAtkinson
- Greetings: Hello
- Message: Hello From Tutorials Point
- Message: Message sent at : on Wednesday, October
二.String 类的属性
String 类有以下两个属性:
2.1 Chars属性:在当前 String 对象中获取 Char 对象的指定位置。
- string s = "Test";
- for (int i= ; i <= s.Length - ; i++ )
- Console.Write("{0} ", s[i]);
- 输出: T e s t
2.2 Length:在当前的 String 对象中获取字符数。
- string characters = "abc\u0000def";
- Console.WriteLine(characters.Length); // Displays 7
三、String 类的方法
String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法
3.1字符串常用的静态方法
3.1.1
方法 :Compare 字符串的比较(按照字典顺序)
方法名称:public static int Compare( string strA, string strB )
描述 :比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。
示例 :
- int result= string.Compare(string str1,string str2);
- 当str1 > str2时,返回1
- 当str1 = str2时,返回0
- 当str1 < str2时,返回-
- string.Compare(string str1,string str2,bool ignoreCase) //忽略大小写比较
- string s1 = "ani\u00ADmal";
- string s2 = "animal";
- Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
- s1, s2, String.Compare(s1, s2));
- 输出为0
- 原因:
- 字符集包括可忽略的字符。 Compare(String,String)方法在执行文化敏感比较时不考虑这些字符。 例如,如果以下代码在.NET Framework 4或更高版本上运行,则“动物”与“动画”(使用软连字符或U + 00AD)的文化敏感比较表明这两个字符串是相当量。
详见:ASCII码对照表
3.1.2
方法:Concat连接方法参数很多,常用的Concat(string str1,string str2);
方法名称:public static string Concat( string str0, string str1 )
描述:连接两个 string 对象。
示例:
- string str=string.Concat("w","e"); //str="we";
3.1.3
方法:Format参数化处理,相当于Console.WriteLine();
方法名称:public static string Format( string format, Object arg0 )
描述:把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。
示例:
- string str=String.Format("今天{0}很热","天气");//str="今天天气很热";
- Console.WriteLine(str);
3.1.4
方法:IsNullOrEmpty判断字符是否为null或者为空,返回值为bool;
方法名称:public static bool IsNullOrEmpty( string value )
描述:指示指定的字符串是否为 null 或者是否为一个空的字符串。
示例:
- string str1="hahha";
- bool b1=string.IsNullOrEmpty(str);//b1=false;
- string str2="";
- bool b2=string.IsNullOrEmpty(str2);//b2=true;
- string str3=null;
- bool b3=string.IsNullOrEmpty(str3);//b3=true;
3.1.5
方法:Join字符串的合并
方法名称:public static string Join( string separator, string[] value )
描述:连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。
示例:
- using System;
- namespace StringApplication
- {
- class StringProg
- {
- static void Main(string[] args)
- {
- string[] starray = new string[]{"Down the way nights are dark",
- "And the sun shines daily on the mountain top",
- "I took a trip on a sailing ship",
- "And when I reached Jamaica",
- "I made a stop"};
- string str = String.Join("\n", starray);
- Console.WriteLine(str);
- Console.ReadKey() ;
- }
- }
- }
- 当上面的代码被编译和执行时,它会产生下列结果:
- Down the way nights are dark
- And the sun shines daily on the mountain top
- I took a trip on a sailing ship
- And when I reached Jamaica
- I made a stop
3.2 字符串常用的实例方法
3.2.1
方法:Contains 判断字符串中是否包含某个字符,返回bool值。
方法名称:public bool Contains( string value )
描述:返回一个表示指定 string 对象是否出现在字符串中的值。
示例:
- using System;
- namespace StringApplication
- {
- class StringProg
- {
- static void Main(string[] args)
- {
- string str = "This is test";
- if (str.Contains("test"))
- {
- Console.WriteLine("The sequence 'test' was found.");
- }
- Console.ReadKey() ;
- }
- }
- }
- 当上面的代码被编译和执行时,它会产生下列结果:
- The sequence 'test' was found.
3.2.2
方法:EndsWith和StartsWith 判断是否是已某种字符串开始或者结束
方法名称:public bool EndsWith( string value )
描述:判断 string 对象的结尾是否匹配指定的字符串。
方法名称:public bool StartsWith( string value )
描述:判断字符串实例的开头是否匹配指定的字符串。
示例:
- string str="好大的雨呀";
- bool b1=str.StartsWith("大");//b1=false;
- bool b2-str.EndsWith("呀");//b2=true;
3.2.3
方法:Equals 比较两个字符串是否相等
方法名称:public static bool Equals( string a, string b )
描述:判断两个指定的 string 对象是否具有相同的值。
示例:
- string str1="asd";
- string str2="ert";
- bool b = str1.Equals(str2); //b=false;
- bool <strName>.Equals(string str, StringComparison.OrdinalIgnoreCase) //表示不区分大小写
3.2.4
方法:IndexOf 和 LastIndexOf 判断字符串第一次出现(IndexOf)和最后一次出现(LastIndexOf )的位置,如果没有出现过则返回值为-1
方法名称:
描述:
public int IndexOf( char value )
返回指定 Unicode 字符在当前字符串中第一次出现的索引,索引从 0 开始。
public int IndexOf( string value )
返回指定字符串在该实例中第一次出现的索引,索引从 0 开始。
public int IndexOf( char value, int startIndex )
返回指定 Unicode 字符从该字符串中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
public int IndexOf( string value, int startIndex )
返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
public int LastIndexOf( char value )
返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
public int LastIndexOf( string value )
返回指定字符串在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
示例:
- string str ="今天的雨很大,天很冷";
- int i=str.IndexOf("很"); //i=4;
- int i=str.LastIndexOf("很");//j=8;
- int m=str.IndexOf("小");//m=-1;
3.2.5
方法:Replace 字符串(字符也是可以的)替换,返回新的字符串
方法名称:
描述:
public string Replace( char oldChar, char newChar )
把当前 string 对象中,所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符,并返回新的字符串。
public string Replace( string oldValue, string newValue )
把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。
示例:
- s ="A_B_C_D";
- Console.WriteLine(s.Replace('_', '-')); // 把字符串中的'_'字符替换为'-',输出"A-B-C-D"
- Console.WriteLine(s.Replace("_", "")); // 把字符串中的"_"替换为空字符串,输出"A B C D"
- Console.WriteLine();
3.2.6
方法:Insert 插入 在字符串的index位置上插入字符,原来的字符依次后移,变成一个新的字符串
方法名称:public string Insert( int startIndex, string value )
描述:返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。
示例:
- string str="夜深了";
- string s=str.Insert(,"已经");// s="夜已经深了"
3.2.7
方法:Remove删除字符串(字符)
方法名称:
描述:
public string Remove( int startIndex )
移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。
public string Remove( int startIndex, int count )
从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。
示例:
- string str="夜已经深了";
- string s=str.Remove(,);//s="夜深了";
3.2.8
方法:Split 将字符串<strName>以sep数组中的字符分割,分割后得到的内容存到一个数组中(string[] <strName>.Split(params char[] sep);)
方法名称:
描述:
public string[] Split( params char[] separator )
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。
public string[] Split( char[] separator, int count )
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。
示例:
- string str="我,真的、好困;呀";
- string[] s=str.Split(new char(){',','、',';'});//s=string[]{"我","真的","好困","呀"};
3.2.9
方法:Substring 截取字符<str>以index开始截取,并截取lenth个字符(string <str>.Substring(index,lenth))
示例:
- string str="还在下雨";
- string s=str.Substring(,);//s="下雨";
- s ="ABCD";
- Console.WriteLine(s.Substring()); // 从第2位开始(索引从0开始)截取一直到字符串结束,输出"BCD"
- Console.WriteLine(s.Substring(, )); // 从第2位开始截取2位,输出"BC"
- Console.WriteLine();
3.2.10
方法:ToCharArray将字符串转化为字符数组(<string>.ToCharArray())
方法名称:
描述:
public char[] ToCharArray()
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。
public char[] ToCharArray( int startIndex, int length )
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。
示例:
- //打散为字符数组(ToCharArray)
- s ="ABCD";
- char[] arr = s.ToCharArray(); // 把字符串打散成字符数组{'A','B','C','D'}
- Console.WriteLine(arr[]); // 输出数组的第一个元素,输出"A"
- Console.WriteLine();
3.2.11
方法:Trim() 出去两边的空格
方法名称:
public string Trim()
描述:移除当前 String 对象中的所有前导空白字符和后置空白字符。
示例(补充):
- string str=" dd ";
- string s=str.Trim();//s="dd";
- 截头去尾(Trim)
- s ="__AB__CD__";
- Console.WriteLine(s.Trim('_')); // 移除字符串中头部和尾部的'_'字符,输出"AB__CD"
- Console.WriteLine(s.TrimStart('_')); // 移除字符串中头部的'_'字符,输出"AB__CD__"
- Console.WriteLine(s.TrimEnd('_')); // 移除字符串中尾部的'_'字符,输出"__AB__CD"
- Console.WriteLine();
3.2.12
方法:ToUpper(转换为大写)和ToLower(转换为小写)
方法名称:
描述:
public string ToLower()
把字符串转换为小写并返回。
public string ToUpper()
把字符串转换为大写并返回。
示例:
- string s="RaSer";
- string s1=s.ToUpper();//s1="RASER";
- string s2=s.ToLower();//s2="raser";
3.2.13
方法:填充对齐(PadLeft和PadRight)
示例:
- s ="ABCD";
- Console.WriteLine(s.PadLeft(, '_')); // 使用'_'填充字符串左部,使它扩充到6位总长度,输出"__ABCD"
- Console.WriteLine(s.PadRight(, '_')); // 使用'_'填充字符串右部,使它扩充到6位总长度,输出"ABCD__"
- Console.WriteLine();
【2】DateTime 数字型
- 方法:System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
- currentTime=System.DateTime.Now;
1.2 取当前年/月/日/时/分/秒/毫秒
- int 年=currentTime.Year;//.Day//.Hour//.Minute//.Second//.Millisecond
1.3 取中文日期显示——年月日时分
- string strY=currentTime.ToString("f"); //不显示秒
1.4 取中文日期显示_年月
- string strYM=currentTime.ToString("y");
1.5 取中文日期显示_月日
- string strMD=currentTime.ToString("m");
1.6 取当前年月日,格式为:2003-9-23
- string strYMD=currentTime.ToString("d");
1.7 取当前时分,格式为:14:24
- string strT=currentTime.ToString("t");
【3】字符型转换位数字型
- Int32.Parse(变量) Int32.Parse("常量")
【4】变量.ToString()
- 字符型转换 转为字符串
- .ToString("n"); //生成 12,345.00
- .ToString("C"); //生成 ¥12,345.00
- .ToString("e"); //生成 1.234500e+004
- .ToString("f4"); //生成 12345.0000
- .ToString("x"); //生成 3039 (16进制)
- .ToString("p"); //生成 1,234,500.00%
【5】字码转换转为比特码
- System.Text.Encoding.Default.GetBytes(变量)
- 如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
- 然后可得到比特长度:
- len = bytStr.Length;
【6】System.Text.StringBuilder("")
- 如:
- System.Text.StringBuilder sb = new System.Text.StringBuilder("");
- sb.Append("中华");
- sb.Append("人民");
- sb.Append("共和国");
【7】把字符转为数字,查代码点,注意是单引号。
- (int)'字符'
- 如: console.Write((int)'中'); //结果为中字的代码:20013
【8】把数字转为字符,查代码代表的字符:(char)代码
- console.Write((char)); //返回“国”字。
【9】取i与j中的最大值:Math.Max(i,j)
- 如 int x=Math.Max(,); // x将取值 10
【10】反转整个一维Array中元素的顺序
- char[] charArray = "abcde".ToCharArray();
- Array.Reverse(charArray);
- Console.WriteLine(new string(charArray));
【11】判断一个字符串中的第n个字符是否是大写
- string str="abcEEDddd";
- Response.Write(Char.IsUpper(str,));
参考文章:
2.菜鸟教程
3.http://dev.yesky.com/msdn/407/2261407.shtml

友情提示
作者:mhq_martin
博客园地址:http://www.cnblogs.com/mhq-martin/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【终结版】C#常用函数和方法集汇总的更多相关文章
- C# 常用函数和方法集汇总
1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...
- c#.net常用函数和方法集
1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...
- C# 常用函数和方法集
1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System. ...
- 汇总c#.net常用函数和方法集
1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...
- 《zw版·Halcon-delphi系列原创教程》 zw版-Halcon常用函数Top100中文速查手册
<zw版·Halcon-delphi系列原创教程> zw版-Halcon常用函数Top100中文速查手册 Halcon函数库非常庞大,v11版有1900多个算子(函数). 这个Top版,对 ...
- jquery常用函数与方法汇总
1.delay(duration,[queueName]) 设置一个延时来推迟执行队列中之后的项目. jQuery1.4新增.用于将队列中的函数延时执行.他既可以推迟动画队列的执行,也可以用于自定义队 ...
- opencv-学习笔记(1)常用函数和方法。
opencv-学习笔记(1)常用函数和方法. cv2.imread(filename,falg) filename是文件名字 flag是读入的方式 cv2.MREAD_UNCHANGED :不进行转化 ...
- Python | Python常用函数、方法示例总结(API)
目录 前言 1. 运算相关 2. Sring与数字 3. 列表相关 4. 集合相关 5. 序列化类型 6. 字典相关 7. 输入输出 8. 文件相关 9. json模块 10. unittest测试模 ...
- C++常用字符串分割方法实例汇总
投稿:shichen2014 字体:[增加 减小] 类型:转载 时间:2014-10-08我要评论 这篇文章主要介绍了C++常用字符串分割方法实例汇总,包括了strtok函数.STL.Boost等常用 ...
随机推荐
- JsonParseException:非法的unquoted字符((CTRL-CHAR,代码9)):必须被转义
其它异常,Could not read document: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped ...
- LazyMan深入解析和实现
一.题目介绍 以下是我copy自网上的面试题原文: 实现一个LazyMan,可以按照以下方式调用: LazyMan("Hank")输出: Hi! This is Hank! ...
- XP环境下C# 调用Pocess.start()时提示文件找不到的错误解决办法
错误提示如下: System.ComponentModel.Win32Exception (0x80004005): 系统找不到指定的文件. 在 System.Diagnostics.Process. ...
- [20171225]查看并行执行计划注意的问题.txt
[20171225]查看并行执行计划注意的问题.txt --//如果使用dbms_xplan.display_cursor查看并行执行计划注意一些问题,通过例子说明: 1.环境: SCOTT@book ...
- 转:npm安装教程
一.使用之前,我们先来掌握3个东西是用来干什么的. npm: Nodejs下的包管理器. webpack: 它主要的用途是通过CommonJS的语法把所有浏览器端需要发布的静态资源做相应的准备,比如资 ...
- Django电商项目---完成商品主页显示day2
利用DjangoAdmin初始化数据库 创建项目 python manage.py startapp df_goods 添加配置 manas/urls.py manas/settings.py 新创建 ...
- 阵列卡raid H730写策略write-through和write-back配置说明
问题描述: 最近公司新进了测试服务器,但是在做阵列的时候忘记写策略里面的配置意思了 就网上查了一下,然后顺便做个笔记记录一下 write-through 数据在写入存储的同时,要写入缓存,这种方式安全 ...
- flask框架的教程--程序的基本结构[二]
一个简单的程序 from flask import Flask # 实例化app 对象 app = Flask(__name__) @app.route('/') def index(): retur ...
- django项目中在settings中配置静态文件
STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] 写成大写可能看不太懂,但是小写的意思非常明显:staticfiles_dir = [ o ...
- SQL2008 一直error40 无法连接到localhost
1. Problem 2. Reason 可能是之前卸载SQL Server时没卸载干净 后来又重新安装时导致默认实例名不能用 就随手写了个SQLMOLORY实例名 但其实系统内这时是有两个SQL实例 ...