C#里面的常用的函数和方法非常重要,然而做题的时候会经常忘记这些封装好的方法,所以我总结一下 C#常用函数和方法集。

【1】C#操作字符串的常用使用方法

在 C# 中,您可以使用字符数组来表示字符串,但是,更常见的做法是使用 string 关键字来声明一个字符串变量。string 关键字是 System.String 类的别名。

一.创建 String 对象

  • 通过给 String 变量指定一个字符串
  • 通过使用 String 类构造函数
  • 通过使用字符串串联运算符( + )
  • 通过检索属性或调用一个返回字符串的方法
  • 通过格式化方法来转换一个值或对象为它的字符串表示形式
  1. using System;
  2.  
  3. namespace StringApplication
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //字符串,字符串连接
  10. string fname, lname;
  11. fname = "Rowan";
  12. lname = "Atkinson";
  13.  
  14. string fullname = fname + lname;
  15. Console.WriteLine("Full Name: {0}", fullname);
  16.  
  17. //通过使用 string 构造函数
  18. char[] letters = { 'H', 'e', 'l', 'l','o' };
  19. string greetings = new string(letters);
  20. Console.WriteLine("Greetings: {0}", greetings);
  21.  
  22. //方法返回字符串
  23. string[] sarray = { "Hello", "From", "Tutorials", "Point" };
  24. string message = String.Join(" ", sarray);
  25. Console.WriteLine("Message: {0}", message);
  26.  
  27. //用于转化值的格式化方法
  28. DateTime waiting = new DateTime(, , , , , );
  29. string chat = String.Format("Message sent at {0:t} on {0:D}",
  30. waiting);
  31. Console.WriteLine("Message: {0}", chat);
  32. Console.ReadKey() ;
  33. }
  34. }
  35. }

结果为:

  1. Full Name: RowanAtkinson
  2. Greetings: Hello
  3. Message: Hello From Tutorials Point
  4. Message: Message sent at : on Wednesday, October

二.String 类的属性

String 类有以下两个属性:

2.1  Chars属性:在当前 String 对象中获取 Char 对象的指定位置。 

  1. string s = "Test";
  2. for (int i= ; i <= s.Length - ; i++ )
  3. Console.Write("{0} ", s[i]);
  4. 输出: T e s t

2.2  Length:在当前的 String 对象中获取字符数。

  1. string characters = "abc\u0000def";
  2. Console.WriteLine(characters.Length); // Displays 7

三、String 类的方法

String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法

3.1字符串常用的静态方法

3.1.1  

方法 :Compare 字符串的比较(按照字典顺序)

方法名称:public static int Compare( string strA, string strB )

描述 :比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。

示例 :

  1. int result= string.Compare(string str1,string str2);
  2.  
  3. str1 > str2时,返回1
  4.  
  5. str1 = str2时,返回0
  6.  
  7. str1 < str2时,返回-
  8.  
  9.     
  10.  
  11. string.Compare(string str1,string str2,bool ignoreCase) //忽略大小写比较
  12. string s1 = "ani\u00ADmal";
  13. string s2 = "animal";
  14. Console.WriteLine("Comparison of '{0}' and '{1}': {2}",
  15. s1, s2, String.Compare(s1, s2));
  16. 输出为0
  17. 原因:
  18. 字符集包括可忽略的字符。 CompareStringString)方法在执行文化敏感比较时不考虑这些字符。 例如,如果以下代码在.NET Framework 4或更高版本上运行,则“动物”与“动画”(使用软连字符或U + 00AD)的文化敏感比较表明这两个字符串是相当量。

详见:ASCII码对照表

 3.1.2

方法:Concat连接方法参数很多,常用的Concat(string str1,string str2);

方法名称:public static string Concat( string str0, string str1 )

描述:连接两个 string 对象。

示例:

  1. string str=string.Concat("w","e"); //str="we";

3.1.3

方法:Format参数化处理,相当于Console.WriteLine();

方法名称:public static string Format( string format, Object arg0 )

描述:把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。

示例:

  1. string str=String.Format("今天{0}很热","天气");//str="今天天气很热";
  2. Console.WriteLine(str);

3.1.4

方法:IsNullOrEmpty判断字符是否为null或者为空,返回值为bool;

方法名称:public static bool IsNullOrEmpty( string value )

描述:指示指定的字符串是否为 null 或者是否为一个空的字符串。

示例:

  1. string str1="hahha";    
  2.  
  3. bool b1=string.IsNullOrEmpty(str);//b1=false;
  4.  
  5. string str2="";
  6.  
  7. bool b2=string.IsNullOrEmpty(str2);//b2=true;
  8.  
  9. string str3=null;
  10.  
  11. bool b3=string.IsNullOrEmpty(str3);//b3=true;

 3.1.5

方法:Join字符串的合并

方法名称:public static string Join( string separator, string[] value )

描述:连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。

示例:

  1. using System;
  2.  
  3. namespace StringApplication
  4. {
  5. class StringProg
  6. {
  7. static void Main(string[] args)
  8. {
  9. string[] starray = new string[]{"Down the way nights are dark",
  10. "And the sun shines daily on the mountain top",
  11. "I took a trip on a sailing ship",
  12. "And when I reached Jamaica",
  13. "I made a stop"};
  14.  
  15. string str = String.Join("\n", starray);
  16. Console.WriteLine(str);
  17. Console.ReadKey() ;
  18. }
  19. }
  20. }
  21.  
  22. 当上面的代码被编译和执行时,它会产生下列结果:
  23. Down the way nights are dark
  24. And the sun shines daily on the mountain top
  25. I took a trip on a sailing ship
  26. And when I reached Jamaica
  27. I made a stop

3.2 字符串常用的实例方法

3.2.1

方法:Contains 判断字符串中是否包含某个字符,返回bool值。

方法名称:public bool Contains( string value )

描述:返回一个表示指定 string 对象是否出现在字符串中的值。

示例:

  1. using System;
  2.  
  3. namespace StringApplication
  4. {
  5. class StringProg
  6. {
  7. static void Main(string[] args)
  8. {
  9. string str = "This is test";
  10. if (str.Contains("test"))
  11. {
  12. Console.WriteLine("The sequence 'test' was found.");
  13. }
  14. Console.ReadKey() ;
  15. }
  16. }
  17. }
  18. 当上面的代码被编译和执行时,它会产生下列结果:
  19. The sequence 'test' was found.

3.2.2

方法:EndsWith和StartsWith  判断是否是已某种字符串开始或者结束

方法名称:public bool EndsWith( string value )

描述:判断 string 对象的结尾是否匹配指定的字符串。

方法名称:public bool StartsWith( string value )

描述:判断字符串实例的开头是否匹配指定的字符串。

示例:

  1. string str="好大的雨呀";
  2.  
  3. bool b1=str.StartsWith("大");//b1=false;
  4.  
  5. bool b2-str.EndsWith("呀");//b2=true;

3.2.3

方法:Equals 比较两个字符串是否相等

方法名称:public static bool Equals( string a, string b )

描述:判断两个指定的 string 对象是否具有相同的值。

示例:

  1. string str1="asd";
  2. string str2="ert";
  3. bool b = str1.Equals(str2); //b=false;
  4.  
  5. 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 开始。

示例:

  1. string str ="今天的雨很大,天很冷";
  2.  
  3. int i=str.IndexOf("很"); //i=4;
  4.  
  5. int i=str.LastIndexOf("很");//j=8;
  6. 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 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。

示例:

  1. s ="A_B_C_D";
  2. Console.WriteLine(s.Replace('_', '-')); // 把字符串中的'_'字符替换为'-',输出"A-B-C-D"
  3. Console.WriteLine(s.Replace("_", "")); // 把字符串中的"_"替换为空字符串,输出"A B C D"
  4. Console.WriteLine();

3.2.6

方法:Insert 插入 在字符串的index位置上插入字符,原来的字符依次后移,变成一个新的字符串

方法名称:public string Insert( int startIndex, string value )

描述:返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。

示例:

  1. string str="夜深了";
  2.  
  3. string s=str.Insert(,"已经");// s="夜已经深了"

3.2.7

方法:Remove删除字符串(字符)

方法名称:

描述:

public string Remove( int startIndex )

移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。

public string Remove( int startIndex, int count )

从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。

示例:

  1. string str="夜已经深了";
  2.  
  3. 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 参数指定要返回的子字符串的最大数目。

示例:

  1. string str="我,真的、好困;呀";
  2.  
  3. string[] s=str.Split(new char(){',','、',';'});//s=string[]{"我","真的","好困","呀"};

3.2.9

方法:Substring 截取字符<str>以index开始截取,并截取lenth个字符(string <str>.Substring(index,lenth))

示例:

  1. string str="还在下雨";
  2. string s=str.Substring(,);//s="下雨";
  3.  
  4. s ="ABCD";
  5. Console.WriteLine(s.Substring()); // 从第2位开始(索引从0开始)截取一直到字符串结束,输出"BCD"
  6. Console.WriteLine(s.Substring(, )); // 从第2位开始截取2位,输出"BC"
  7. Console.WriteLine();

3.2.10

方法:ToCharArray将字符串转化为字符数组(<string>.ToCharArray())

方法名称:

描述:

public char[] ToCharArray()

返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。

public char[] ToCharArray( int startIndex, int length )

返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。

示例:

  1. //打散为字符数组(ToCharArray)
  2. s ="ABCD";
  3. char[] arr = s.ToCharArray(); // 把字符串打散成字符数组{'A','B','C','D'}
  4. Console.WriteLine(arr[]); // 输出数组的第一个元素,输出"A"
  5. Console.WriteLine();

3.2.11

方法:Trim() 出去两边的空格

方法名称:

public string Trim()

描述:移除当前 String 对象中的所有前导空白字符和后置空白字符。

示例(补充):

  1. string str=" dd ";
  2. string s=str.Trim();//s="dd";
  3.  
  4. 截头去尾(Trim
  5. s ="__AB__CD__";
  6. Console.WriteLine(s.Trim('_')); // 移除字符串中头部和尾部的'_'字符,输出"AB__CD"
  7. Console.WriteLine(s.TrimStart('_')); // 移除字符串中头部的'_'字符,输出"AB__CD__"
  8. Console.WriteLine(s.TrimEnd('_')); // 移除字符串中尾部的'_'字符,输出"__AB__CD"
  9. Console.WriteLine();

3.2.12

方法:ToUpper(转换为大写)和ToLower(转换为小写)

方法名称:

描述:

public string ToLower()

把字符串转换为小写并返回。

public string ToUpper()

把字符串转换为大写并返回。

示例:

  1. string s="RaSer";
  2.  
  3. string s1=s.ToUpper();//s1="RASER";
  4.  
  5. string s2=s.ToLower();//s2="raser";

3.2.13

方法:填充对齐(PadLeft和PadRight)

示例:

  1. s ="ABCD";
  2. Console.WriteLine(s.PadLeft(, '_')); // 使用'_'填充字符串左部,使它扩充到6位总长度,输出"__ABCD"
  3. Console.WriteLine(s.PadRight(, '_')); // 使用'_'填充字符串右部,使它扩充到6位总长度,输出"ABCD__"
  4. Console.WriteLine();

【2】DateTime 数字型

  1. 方法:System.DateTime currentTime=new System.DateTime();

1.1 取当前年月日时分秒

  1. currentTime=System.DateTime.Now;

1.2 取当前年/月/日/时/分/秒/毫秒

  1. int 年=currentTime.Year;//.Day//.Hour//.Minute//.Second//.Millisecond

1.3 取中文日期显示——年月日时分

  1. string strY=currentTime.ToString("f"); //不显示秒

1.4 取中文日期显示_年月

  1. string strYM=currentTime.ToString("y");

1.5 取中文日期显示_月日

  1. string strMD=currentTime.ToString("m");

1.6 取当前年月日,格式为:2003-9-23

  1. string strYMD=currentTime.ToString("d");

1.7 取当前时分,格式为:14:24

  1. string strT=currentTime.ToString("t");

【3】字符型转换位数字型

  1. Int32.Parse(变量) Int32.Parse("常量")

【4】变量.ToString()

  1. 字符型转换 转为字符串
  2. .ToString("n"); //生成 12,345.00
  3. .ToString("C"); //生成 ¥12,345.00
  4. .ToString("e"); //生成 1.234500e+004
  5. .ToString("f4"); //生成 12345.0000
  6. .ToString("x"); //生成 3039 (16进制)
  7. .ToString("p"); //生成 1,234,500.00%

【5】字码转换转为比特码

  1. System.Text.Encoding.Default.GetBytes(变量)
  2.  
  3. 如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
  4.  
  5. 然后可得到比特长度:
  6.  
  7. len = bytStr.Length;

【6】System.Text.StringBuilder("")

  1. 如:
  2. System.Text.StringBuilder sb = new System.Text.StringBuilder("");
  3. sb.Append("中华");
  4. sb.Append("人民");
  5. sb.Append("共和国");

【7】把字符转为数字,查代码点,注意是单引号。

  1. (int)'字符'
  2.  
  3. 如: console.Write((int)'中'); //结果为中字的代码:20013

【8】把数字转为字符,查代码代表的字符:(char)代码

  1. console.Write((char)); //返回“国”字。

【9】取i与j中的最大值:Math.Max(i,j)

  1. int x=Math.Max(,); // x将取值 10

【10】反转整个一维Array中元素的顺序

  1. char[] charArray = "abcde".ToCharArray();
  2. Array.Reverse(charArray);
  3. Console.WriteLine(new string(charArray));

【11】判断一个字符串中的第n个字符是否是大写

  1. string str="abcEEDddd";
  2. Response.Write(Char.IsUpper(str,));

参考文章:

1.微软文档string类

2.菜鸟教程

3.http://dev.yesky.com/msdn/407/2261407.shtml

友情提示

作者:mhq_martin

博客园地址:http://www.cnblogs.com/mhq-martin/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

【终结版】C#常用函数和方法集汇总的更多相关文章

  1. C# 常用函数和方法集汇总

    1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...

  2. c#.net常用函数和方法集

    1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...

  3. C# 常用函数和方法集

    1.DateTime 数字型  System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System. ...

  4. 汇总c#.net常用函数和方法集

    1.DateTime 数字型 System.DateTime currentTime=new System.DateTime(); 1.1 取当前年月日时分秒 currentTime=System.D ...

  5. 《zw版·Halcon-delphi系列原创教程》 zw版-Halcon常用函数Top100中文速查手册

    <zw版·Halcon-delphi系列原创教程> zw版-Halcon常用函数Top100中文速查手册 Halcon函数库非常庞大,v11版有1900多个算子(函数). 这个Top版,对 ...

  6. jquery常用函数与方法汇总

    1.delay(duration,[queueName]) 设置一个延时来推迟执行队列中之后的项目. jQuery1.4新增.用于将队列中的函数延时执行.他既可以推迟动画队列的执行,也可以用于自定义队 ...

  7. opencv-学习笔记(1)常用函数和方法。

    opencv-学习笔记(1)常用函数和方法. cv2.imread(filename,falg) filename是文件名字 flag是读入的方式 cv2.MREAD_UNCHANGED :不进行转化 ...

  8. Python | Python常用函数、方法示例总结(API)

    目录 前言 1. 运算相关 2. Sring与数字 3. 列表相关 4. 集合相关 5. 序列化类型 6. 字典相关 7. 输入输出 8. 文件相关 9. json模块 10. unittest测试模 ...

  9. C++常用字符串分割方法实例汇总

    投稿:shichen2014 字体:[增加 减小] 类型:转载 时间:2014-10-08我要评论 这篇文章主要介绍了C++常用字符串分割方法实例汇总,包括了strtok函数.STL.Boost等常用 ...

随机推荐

  1. JsonParseException:非法的unquoted字符((CTRL-CHAR,代码9)):必须被转义

     其它异常,Could not read document: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped  ...

  2. LazyMan深入解析和实现

    一.题目介绍  以下是我copy自网上的面试题原文: 实现一个LazyMan,可以按照以下方式调用: LazyMan("Hank")输出: Hi! This is Hank!   ...

  3. XP环境下C# 调用Pocess.start()时提示文件找不到的错误解决办法

    错误提示如下: System.ComponentModel.Win32Exception (0x80004005): 系统找不到指定的文件. 在 System.Diagnostics.Process. ...

  4. [20171225]查看并行执行计划注意的问题.txt

    [20171225]查看并行执行计划注意的问题.txt --//如果使用dbms_xplan.display_cursor查看并行执行计划注意一些问题,通过例子说明: 1.环境: SCOTT@book ...

  5. 转:npm安装教程

    一.使用之前,我们先来掌握3个东西是用来干什么的. npm: Nodejs下的包管理器. webpack: 它主要的用途是通过CommonJS的语法把所有浏览器端需要发布的静态资源做相应的准备,比如资 ...

  6. Django电商项目---完成商品主页显示day2

    利用DjangoAdmin初始化数据库 创建项目 python manage.py startapp df_goods 添加配置 manas/urls.py manas/settings.py 新创建 ...

  7. 阵列卡raid H730写策略write-through和write-back配置说明

    问题描述: 最近公司新进了测试服务器,但是在做阵列的时候忘记写策略里面的配置意思了 就网上查了一下,然后顺便做个笔记记录一下 write-through 数据在写入存储的同时,要写入缓存,这种方式安全 ...

  8. flask框架的教程--程序的基本结构[二]

    一个简单的程序 from flask import Flask # 实例化app 对象 app = Flask(__name__) @app.route('/') def index(): retur ...

  9. django项目中在settings中配置静态文件

    STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] 写成大写可能看不太懂,但是小写的意思非常明显:staticfiles_dir = [ o ...

  10. SQL2008 一直error40 无法连接到localhost

    1. Problem 2. Reason 可能是之前卸载SQL Server时没卸载干净 后来又重新安装时导致默认实例名不能用 就随手写了个SQLMOLORY实例名 但其实系统内这时是有两个SQL实例 ...