- using ConsoleApp1;
- using System;//程式庫呼叫
- using System.Linq.Expressions;
- namespace HelloWorld//創建一個程式庫(自己定義)
- {
- class Program//負責一部分工作的人
- {
- const string dreams = "There are moments in life when you miss someone so much that " +
- "you just want to pick them from your dreams and hug them for real! Dream what " +
- "you want to dream;go where you want to go;be what you want to be,because you have " +
- "only one life and one chance to do all the things you want to do";
- static void Main()//method ..Entry Point 程式進入點
- {
- string word=Console.ReadLine();
- int pos1= dreams.IndexOf(word);
- int pos2= dreams.LastIndexOf(word);
- int length;
- string words;
- if(pos1>=0)//如果有找到起始索引
- {
- if(pos1<pos2)//如果終點索引也有word
- {
- length = pos2;
- // length=(pos2+word.Length)-pos1;//計算這之間的長度
- /*若字串為"This is a book,This abc."
- * 找This字串之間範圍為:This is a book,This,長度為19
- * 起始pos1->0 ,終點pos2->15,找尋為word->"This"
- * 長度->15+4-4
- * 擷取(0,19),
- */
- }
- else//起點與終點一樣
- {
- pos2 = -1;
- length = dreams.Length -pos1;//長度為起始到字串尾
- }
- words= dreams.Substring(pos1, length);//進行擷取
- }
- else
- {
- words = String.Empty;//表空字串
- }
- print(pos1+1,pos2+1,words);
- }
- static void print(int pos1,int pos2,string words)
- {
- Console.WriteLine("first:" + pos1);
- Console.WriteLine("last:" + pos2);
- Console.WriteLine("capture:" + words);
- Console.ReadKey();
- }
- }
- }
複製代碼 |