C#中如何在字符串中查找字符

IndexOf和LastIndexof方法可用于在字符串中找到一个字符的索引。
indexof方法返回基于0的字符的第一次出现的0索引。
如果找到一个字符,它会返回字符的索引;否则返回-1;
该方法具有多种重载的表单,因此可以通过指定字符串中字符的开始和结束位置来应用于整个字符串或者一部分。

LastIndexof方法返回基于0个字符串中找到的字符的0索引。

String authorName = "Onitroad.com World";

Console.WriteLine("Index of first 'W': " + authorName.IndexOf('W'));

Console.WriteLine("Index of 'c' after 5th char: " + authorName.IndexOf('c', 5));

Console.WriteLine("Index of 'o' after 10th char till next 5: " + authorName.IndexOf('o', 10, 5)); Console.WriteLine("Last index of 'a': " + authorName.LastIndexOf('a'));

Console.WriteLine("Last index of 'r': " + authorName.LastIndexOf('r', 5));

Console.WriteLine("Last index of 'r': " + authorName.LastIndexOf('r', 10, 5));
日期:2020-04-11 22:50:29 来源:oir作者:oir