C# 字符串截取

c#中字符串截取使用的方法

String substring(int beginIndex)
String substring(int beginIndex, int endIndex)

String.Substring (Int32)         子字符串從指定的字符位置開始。
String.Substring (Int32, Int32) 子字符串從指定的字符位置開始且具有指定的長度。
舉例如下:
            string s = "Hello C# World!";

            //s1爲從s中截取的位置爲3的字符以後的字符子串,3表示子字符串的起始字符位置
string s1=s.Substring(3);
            //s2爲從s中截取的位置爲6的字符開始長度爲2的字符串,6表示子字符的起始字符位置,2表示子字符長度
string s2 = s.Substring(6, 2);
結果如下:
lo C# World!
C#
int indexOf(String str) 返回第一次出現的指定子字符串在此字符串中的索引。
int indexOf(String str, int fromIndex) 從指定的索引處開始,返回第一次出現的指定子字符串在此字符串中的索引。
int lastIndexOf(String str) 返回在此字符串中最右邊出現的指定子字符串的索引。
int lastIndexOf(String str, int fromIndex) 從指定的索引處開始向後搜索,返回在此字符串中最後一次出現的指定子字符串的索引。
int length() 返回此字符串的長度。
boolean startsWith(String prefix) 測試此字符串是否以指定的前綴開始。
boolean startsWith(String prefix, int toffset) 測試此字符串是否以指定前綴開始,該前綴以指定索引開始。
例如:
 string  str="C:\\Documents and Settings\\Administrator\\桌面\\new1.jpg"
str.Substring(0,str.LastIndexOf("\\")+1)+"new"+str.Substring(str.LastIndexOf("\\")+1,
 str.LastIndexOf(".")-str.LastIndexOf("\\")-1)+str.Substring(str.LastIndexOf("."),str.Length-str.LastIndexOf(".")
str.LastIndexOf("\\")——得到最後一個“\\”的索引值
str.Substring(0,str.LastIndexOf("\\")+1)——得到  C:\\Documents and Settings\\Administrator\\桌面\\
str.Substring(str.LastIndexOf("\\")+1,str.LastIndexOf(".")-str.LastIndexOf("\\")-1)  ——得到 new1

str.Substring(str.LastIndexOf("."),str.Length-str.LastIndexOf(".") ——得到 .jpg




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章