返回列表 發帖
  1. using ConsoleApp1;
  2. using System;//程式庫呼叫
  3. using System.Linq.Expressions;

  4. namespace HelloWorld//創建一個程式庫(自己定義)
  5. {
  6.     class Program//負責一部分工作的人
  7.     {
  8.        const string dreams = "There are moments in life when you miss someone so much that " +
  9.             "you just want to pick them from your dreams and hug them for real! Dream what " +
  10.             "you want to dream;go where you want to go;be what you want to be,because you have " +
  11.             "only one life and one chance to do all the things you want to do";
  12.         static void Main()//method ..Entry Point 程式進入點
  13.         {
  14.             string word=Console.ReadLine();
  15.             int pos1= dreams.IndexOf(word);
  16.             int pos2= dreams.LastIndexOf(word);
  17.             int length;
  18.             string words;
  19.             if(pos1>=0)//如果有找到起始索引
  20.             {
  21.                 if(pos1<pos2)//如果終點索引也有word
  22.                 {
  23.                     length = pos2;
  24.                   // length=(pos2+word.Length)-pos1;//計算這之間的長度
  25.                     /*若字串為"This is a book,This abc."
  26.                      * 找This字串之間範圍為:This is a book,This,長度為19
  27.                      * 起始pos1->0 ,終點pos2->15,找尋為word->"This"
  28.                      * 長度->15+4-4
  29.                      * 擷取(0,19),
  30.                      */
  31.                 }
  32.                 else//起點與終點一樣
  33.                 {
  34.                     pos2 = -1;
  35.                     length = dreams.Length -pos1;//長度為起始到字串尾
  36.                 }
  37.                 words= dreams.Substring(pos1, length);//進行擷取
  38.             }
  39.             else
  40.             {
  41.                 words = String.Empty;//表空字串
  42.             }
  43.             print(pos1+1,pos2+1,words);
  44.         }
  45.         static void print(int pos1,int pos2,string words)
  46.         {
  47.             Console.WriteLine("first:" + pos1);
  48.             Console.WriteLine("last:" + pos2);
  49.             Console.WriteLine("capture:" + words);
  50.             Console.ReadKey();
  51.         }

  52.     }

  53. }
複製代碼
istak.teach2@gmail.com

TOP

返回列表