输出的结果为:this is a string
THIS IS A STRING
九、字符串的查找
字符串的查找是通过IndexOf方法和LastIndexOf方法实现的。其格式为:
字符串.IndexOf(要查找的字符或字符串)
字符串.LastIndexOf(要查找的字符或字符串)
其中,IndexOf方法是返回要查找的字符或字符串第一次在所要查找的字符串出现的位置,LastIndexOf方法是返回要查找的字符或字符串最后一次在所要查找的字符串中出现的位置。IndexOf方法和LastIndexOf方法都返回一个整数,如果在所要查找的字符串内不包含要查找的字符或字符串则返回一个负数。
例九,实现字符串str的查找
?
- <span style="font-size:18px;">using System; using System.Collections.Generic;
- using System.Linq; using System.Text;
- using System.Threading.Tasks;
- namespace 字符串 {
- class Program {
- static void Main(string[] args) {
- string str = "This is a string"; int rh1 = str.IndexOf("i");
- int rh2 = str.LastIndexOf("i"); if (rh1>=0)
- { Console.WriteLine("字符i在字符串str第一次出现的位置是:{0}",rh1);
- Console.WriteLine("字符i在字符串str最后一次出现的位置是:{0}", rh2); }
- else {
- Console.WriteLine("字符i在字符串str未出现"); }
- Console.ReadLine(); }
- } }</span>
输出的结果为:字符i在字符串str第一次出现的位置是:2










