C# Substring的用法

方法1   Substring(Int32)       从此实例检索子字符串。 子字符串在指定的字符位置开始并一直到该字符串的末尾。

方法2   Substring(Int32, Int32)   从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。

参数一:起始位置(从0开始)

参数二:指定长度

用法:string变量名.Substring(参数一, 参数二);

 

举例:

string s = "hello world";

string ss;

 

例子1 //从指定位置开始到结尾的字符串(0位开始)

int i=1;

ss = s.Substring(i);

ss = "ello world"

例子2 //从指定位置开始取固定长度的字符串

int i=1;

ss = s.Substring(i,3);

ss = "ell"

例子3 //返回左边的i个字符

int i=5;

ss = s.Substring(0,i)

ss = "hello"

例子4 //返回右边的i个字符

int i=5;

ss = s.Substring(s.Length-i,i);

ss = "world"

例子5 //返回两个特定字符之间的字符串

int IndexofA = s.IndexOf('e'); //字符串的话总以第一位为指定位置

int IndexofB = s.IndexOf('r');

ss = s.Substring(IndexofA + 1, IndexofB - IndexofA -1);

ss = "llo wo"

猜你喜欢

转载自www.cnblogs.com/net-sky/p/12126335.html