C#幾個經常用到的字符串的截取


 1 string str="123abc456";
 2 int i=3;
 3 1 取字符串的前i個字符
 4    str=str.Substring(0,i); // or  str=str.Remove(i,str.Length-i); 
 5 2 去掉字符串的前i個字符:
 6    str=str.Remove(0,i);  // or str=str.Substring(i); 
 7 3 從右邊開始取i個字符:
 8   str=str.Substring(str.Length-i); // or str=str.Remove(0,str.Length-i);
 9 4 從右邊開始去掉i個字符:
10    str=str.Substring(0,str.Length-i); // or str=str.Remove(str.Length-i,i);
11 5 判斷字符串中是否有"abc" 有則去掉之
12    using System.Text.RegularExpressions;
13    string str = "123abc456";
14    string a="abc";
15    Regex r = new  Regex(a); 
16    Match m = r.Match(str); 
17    if (m.Success)
18    {
19     //下面兩個取一種即可。
20       str=str.Replace(a,"");
21       Response.Write(str);   
22       string str1,str2;
23       str1=str.Substring(0,m.Index);
24       str2=str.Substring(m.Index+a.Length,str.Length-a.Length-m.Index);
25       Response.Write(str1+str2); 
26    }
27 6 如果字符串中有"abc"則替換成"ABC"
28    str=str.Replace("abc","ABC");
29 
30 ************************************************
31 
32 string str="adcdef"; int indexStart = str.IndexOf("d");
33 
34 int endIndex =str.IndexOf("e");
35 
36 string toStr = str.SubString(indexStart,endIndex-indexStart);
37 
38 c#截取字符串最后一個字符的問題!
39 
40 str1.Substring(str1.LastIndexOf(",")+1);
41 
42 C# 截取字符串最后一個字符
43 
44 k = k.Substring(k.Length-1, 1);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM