System.String使用从0看是的序号索引,来定位字符串中的单个字符,所以,可以利用访问数组的方式来定位字符
代码如下
string str = "这是一个定位字符串的示例";
Console.WriteLine(str);
Console.WriteLine("索引值为1的字符串为{0}",str[1]);
Console.WriteLine("索引值为4的字符串为{0}",str[4]);
Console.WriteLine("用String类型实现了IEnumerable<char>和IEnumerable接口,所以,可以用foeeach遍历");
foreach (char item in str)
{
Console.Write(item);
}
上面我用foreach遍历这个字符串因为在System.String中实现了IEnumerable<char>泛型接口和IEnumerable接口,也可以使用for来遍历。
为了定位字符串子串,System.String 中提供了很多的方法来实现这个功能,其中比较常用的是SubString方法,在Substring方法是实例的方法,具有两种重载形式。
//获取从指定索引开始的子字符串,
public string Substring(int StartIndex)
//获取从制定的索引开始,并具有定长的子串
public string SubString(int StartIndex ,int length)
另外system.String 中提还提供了, StartWith,EndWith, IndexOf, indexOfAny,LastindexOf,LastindexOfAny 下面举一个综合的实例演示这些方法。
string str = "++这是一个综合使用定位字符串方法的C#示例++";
Console.WriteLine(str);
Console.WriteLine("从字符串中过滤掉++字符");
// 使用TrimStart和TrimEnd截取指定字符数组的字符
string tempstr = str.TrimStart("++".ToCharArray()).TrimEnd("++".ToCharArray());
Console.WriteLine("使用TrimStart和TrimEnd截取指定字符数组的字符{0}的结果",tempstr);
//使用Substring 方法截取字符串中的指定字符
tempstr = str.Substring(0, str.LastIndexOfAny("++".ToCharArray()) - 1);
tempstr = str.Substring(0, str.LastIndexOfAny("++".ToCharArray()) + 1);
Console.WriteLine("使用Substrin的实现结果是{0}",tempstr);
Console.WriteLine("使用StartWith与EndWith方法");
// 判断指定的字符串++是否从str字符串的开头,如果是返回true 否则返回false
if (str.StartsWith("++"))
{
Console.WriteLine("字符串以子串++作为开头");
}
// 判断指定的字符串++是否从str字符串的结束,如果是返回true 否则返回false
if (str.EndsWith("++"))
{
Console.WriteLine("这个是以子串++结尾");
}
// 获取指定的字符串+在字符串str中位置,如果存在返回字符串中的索引
Console.WriteLine("str.IndexOf方法");
int i = str.IndexOf("+");
if (i >= 0 )
{
Console.WriteLine("+字符存在与str字符串中,索引位置是{0}",i);
}
else
{
Console.WriteLine("+字符不存在与str字符串中");
}
Console.WriteLine("str.IndexOfAny()");
//获取指定字符数组++在字符串的位置,如果存在,则返回字符串中的索引
i = str.IndexOfAny("++".ToCharArray(), 0, str.Length - 1);
if (i >= 0)
{
Console.WriteLine("++字符存在与str字符串中,索引位置是{0}", i);
}
else
{
Console.WriteLine("++字符不存在与str字符串中");
}
Console.WriteLine("str.LastIndexOf()");
i = str.LastIndexOf("+");
if (i >= 0)
{
Console.WriteLine("+字符存在与str字符串中,索引位置是{0}", i);
}
else
{
Console.WriteLine("+字符不存在与str字符串中");
}