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();
            }
posted @ 2017-03-07 17:29  Kkky  阅读(12115)  评论(0编辑  收藏  举报