返回列表 發帖

C# 7 105 字串索引

TQC+ 物件導向程式語言
最新一次更新時間:2024-01-05 11:45:19

1. 題目說明:
請新增一個主控台應用程式,加入C:\ANS.CSF\CS01資料夾中的CSD01.cs進行編寫。依下列題意進行作答:輸入一個字串,再於題目提供的英文短文中尋找及輸出所在位置,使輸出值符合題意要求。檔案名稱請另存新檔為CSA01.cs,儲存於C:\ANS.CSF\CS01資料夾,再進行評分。

2. 設計說明:
專案中已提供一段英文短文於常數dreams中。
請在Main主程式中,讓使用者輸入單字,以輸入的單字在常數dreams英文短文中,尋找第一個位置及最後一個位置,再取出這兩個位置間的字串,將此三個值傳至print程式進行輸出。
* 提示:字串索引由0開始,輸出值必須加1。
若輸入不存在的單字,位置必須顯示為0,擷取字串為空值(無空格);若單字只出現一次,則擷取單字之後的所有文字。
3. 輸入輸出:
輸入說明
一個字串

輸出說明
第一個位置first
最後一個位置last
擷取兩個位置之間的字串capture(輸出最後一行後不自動換行)

範例輸入1
want
範例輸出1
first:71
last:276
capture: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

範例輸入2
things
範例輸出2
first:265
last:0
capture:things you want to do

範例輸入3
substring
範例輸出3
first:0
last:0
capture:

4. 評分項目:
(1) 符合設計說明輸出正確格式配分        10
May

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Drawing;

  7. namespace CSA01
  8. {
  9.     class CSA01
  10.     {
  11.         const string dreams = "There are moments in life when you miss someone so much that " +
  12.             "you just want to pick them from your dreams and hug them for real! Dream what " +
  13.             "you want to dream;go where you want to go;be what you want to be,because you have " +
  14.             "only one life and one chance to do all the things you want to do";
  15.         static void Main(string[] args)
  16.         {
  17.             string word = Console.ReadLine();
  18.             int pos1 = dreams.IndexOf(word);
  19.             int pos2 = dreams.LastIndexOf(word);
  20.             int length;
  21.             string words;

  22.             if (pos1 >= 0)
  23.             {
  24.                 if (pos1 < pos2)
  25.                 {
  26.                     length = (pos2 + word.Length) - pos1;
  27.                 }
  28.                 else
  29.                 {
  30.                     pos2 = -1;
  31.                     length = dreams.Length - pos1;
  32.                 }
  33.                 words = dreams.Substring(pos1, length);
  34.             }
  35.             else
  36.             {
  37.                 words = String.Empty;
  38.             }
  39.             print(pos1 + 1, pos2 + 1, words);
  40.         }
  41.         static void print(int pos1, int pos2, string words)
  42.         {//pos1=>first,pos2=>last,words=>capture
  43.             Console.WriteLine("first:" + pos1);
  44.             Console.WriteLine("last:" + pos2);
  45.             Console.Write("capture:" + words);
  46.             Console.ReadKey();
  47.         }
  48.     }
  49. }
複製代碼
May

TOP

返回列表