轻松学习C#的String类

2019-12-26 15:15:28刘景俊

输出的结果为:this is a string
                       THIS IS A STRING
九、字符串的查找
         字符串的查找是通过IndexOf方法和LastIndexOf方法实现的。其格式为:
         字符串.IndexOf(要查找的字符或字符串)
         字符串.LastIndexOf(要查找的字符或字符串)
         其中,IndexOf方法是返回要查找的字符或字符串第一次在所要查找的字符串出现的位置,LastIndexOf方法是返回要查找的字符或字符串最后一次在所要查找的字符串中出现的位置。IndexOf方法和LastIndexOf方法都返回一个整数,如果在所要查找的字符串内不包含要查找的字符或字符串则返回一个负数。
例九,实现字符串str的查找
 

  1. <span style="font-size:18px;">using System;   using System.Collections.Generic;  
  2. using System.Linq;   using System.Text;  
  3. using System.Threading.Tasks;     
  4. namespace 字符串   {  
  5.  class Program    {  
  6.  static void Main(string[] args)    {  
  7.   string str = "This is a string";     int rh1 = str.IndexOf("i");  
  8.   int rh2 = str.LastIndexOf("i");     if (rh1>=0)  
  9.   {     Console.WriteLine("字符i在字符串str第一次出现的位置是:{0}",rh1);  
  10.   Console.WriteLine("字符i在字符串str最后一次出现的位置是:{0}", rh2);     }  
  11.   else    {  
  12.   Console.WriteLine("字符i在字符串str未出现");     }  
  13.   Console.ReadLine();    }  
  14.  }   }</span>  
?

输出的结果为:字符i在字符串str第一次出现的位置是:2