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

C#字符串操作示例
本文介绍了C#中使用String.IndexOf、String.LastIndexOf和String.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();
            }

转载于:https://www.cnblogs.com/kkkky/p/6515890.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值