C#字符串相关函数(持续更新,绝不TJ)

来源:互联网 发布:q币赚钱软件 编辑:程序博客网 时间:2024/04/30 22:02

1.字符窜截取函数 string.Substring()

1.1 Substring(int a):在a位置开始截取,直到字符串结束(开始是0);

eg: string str = "abcde";

 string str1=str.Substring(1);

str1的结果是:"bcde"

1.2 Substring(int a,int b):在a位置开始截取,截取b长度的字符串;

eg:string str="abcde";

 string str1=str.Substring(1,2);

str1的结果是:"bc"


2. 查找字符串中子字符串出先的位置函数 string.IndexOf(string str):

2.1 IndexOf(string str):查找str首次出现的位置,如果没有返回值是-1

eg:string sa="abcdeabc";

  int n=sa.IndexOf("bc");

  n的结果是1.

2.2 IndexOf(string str,int a):在a位置开始查找字符串出现的位置。

  eg:string sa="abcdeabc";

    int n=sa.IndexOf("bc",2);

  n的结果是:6.


3 查找字符创中子字符串出现的位置,但是是从后面开始的LastIndexOf(string str).

3.1 LastIndexOf(string str):从后面开始查找str首次出现的位置,没有则返回-1.

  eg:string sa="abcdeabc";

   int n = sa.LastIndexOf("bc");

   n的结果是:6

3.2 LastIndexOf(string str,int a):从a位置开始向前查找str出现的位置。

  eg string sa="abcdeabc";

   int n = sa.LastIndexOf("bc",6);

   n的结果是:1。


4 检测字符串开头/结尾的函数StartsWith(string str)/EndsWith(string str) ,返回值是布尔型的。

4.1 StartsWith(string str):判断字符串是不是以str开头的。

  eg  string sa="abcdef";

     sa.StartsWith("ab");//结果是 True

     sa.StartsWith("ac");//结果是 False

4.2 EndsWith(string str):判断字符串是不是以str结尾的。

  eg  string sa="abcdef";

    sa.EndsWith("ef");//结果是 True

    sa.EndsWith("ff");//结果是 False


5 计算字符串长度的函数 Length,返回int类型的数据。

  eg  string sa="abcde";

     int n = sa.Length;

    n的结果是:5。


原创粉丝点击