C#利用String類的IndexOf、LastIndexOf、Substring截取字符串


一、String.IndexOf

String.IndexOf 方法 (Char, Int32, Int32)
報告指定字符在此實例中的第一個匹配項的索引(從0開始)。搜索從指定字符位置開始,並檢查指定數量的字符位置。
String.IndexOf(value, startIndex, count)

參數
value:要查找的 Unicode 字符。 
startIndex:搜索起始位置。 
count:要檢查的字符位置數。
返回值(Int32):
如果找到該字符,則為 value 的索引位置;否則如果未找到,則為 -1。


 二、String.LastIndexOf

String.LastIndexOf 方法
報告指定的 Unicode 字符或 String 在此實例中的最后一個匹配項的索引位置。


 三、String.Substring

String.Substring 方法
從此實例檢索子字符串。 

 

名稱 說明
String.Substring (Int32) 從此實例檢索子字符串。子字符串從指定的字符位置開始。
String.Substring (Int32, Int32) 從此實例檢索子字符串。子字符串從指定的字符位置開始且具有指定的長度。


 

例:讀取文件內容,並以“$”和“#”為索引截取字符串。

文件內容為:

1$AID_700e5984dba96744
2$AID_b5f0d8ca79ae856e#AID_700e5984dba96744
3$AID_2f0b6558766df9b6#AID_b5f0d8ca79ae856e

		if (!File.Exists(CablewayContants.CLIENTS_FILE_NAME))
            {
                throw new Exception("Fatal Error: File NOT Found");
            }
            else
            {
                StreamReader sr = new StreamReader(CablewayContants.CLIENTS_FILE_NAME, Encoding.UTF8);
                string s;
                while ((s = sr.ReadLine()) != null)
                {
                    int splitIndex = s.IndexOf("$");
                    int splitIndex2 = s.LastIndexOf("#");
                    if (splitIndex > 0)
                    {
                        string lDeviceName = s.Substring(0, splitIndex);
                        string lDeviceID = null;
                        string lDeviceNeighbourID = null;
                        if (splitIndex2 > 0)
                        {
							// 根據“$”和“#”的索引截取"AID_700e5984dba96744"
							lDeviceID = s.Substring(splitIndex + 1, splitIndex2 - splitIndex - 1);
                            lDeviceNeighbourID = s.Substring(splitIndex2 + 1);
                        }
                        else
                        {
                            lDeviceID = s.Substring(splitIndex + 1);
                        }
                    }
                }
                sr.Close();
            }


免責聲明!

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



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