Re: [問題] 擷取檔案名稱後只想輸出前段字元

看板C_and_CPP作者 (髮箍)時間3年前 (2020/11/14 14:52), 3年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/2 (看更多)
※ 引述《lazy0813 (菜邊巴)》之銘言: : 開發平台(Platform): Win10 : 編譯器:Dev-C++ : 問題(Question): : 小弟目前是C初學者,我想請教版上各位先進。 : 我目前想要把文件中的檔案名稱擷取前面幾個字元建立成一份清單, : 但是不知道該怎麼做,目前想法是應該把字串轉為字元。 : btw,檔案名稱為:20110827001040.00.led.01.00-03.00h.jpg : 想擷取為20110827001040.00.led.01.00-03.00h 以下恕刪 這看起來比較像是邏輯思考和資源利用問題, 而不是實作問題. 根據你的描述 , 原始檔名可以標記成兩個部分: 20110827001040.00.led.01.00-03.00h.jpg 紫色是你想擷取的部分, 而綠色是已知副檔名. 我們可以用二分法來處理它: 如果能找出紫色的範圍 (原問題), 我們也能知道綠色有哪些字元; 相反地, 若我們找出.jpg出現在哪裡, 要擷取的字串也就呼之欲出. 要在字串裡面找字串, 可以先找看看標準函式庫裡有沒有現成的工具, 它們的 宣告放在 <string.h> 裡, 大致的描述可以在 cppreference 找到: String handling https://en.cppreference.com/w/c/string/byte 點進去在眾多的說明裡, 你可以找到和我們目標相符的函式: strstr() strstr finds the first occurrence of a substring of characters (function) https://en.cppreference.com/w/c/string/byte/strstr 看完裡面的範例程式, 我們就可以做個實驗看看能否利用 strstr() 來找到 .jpg字串, 從而找出要擷取的字串: #include <stddef.h> #include <stdio.h> #include <string.h> const char filename[] = "20110827001040.00.led.01.00-03.00h.jpg"; const char* const extenstion = strstr(filename, ".jpg"); // get sub-string length before ".jpg" const size_t length = (extenstion - filename); // print sub-string with specific length printf("%.*s", length, filename); 接著就是根據實際需求去做修改了. -- [P1389R1] Standing Document for SG20: Guidelines for Teaching C++ to Beginners https://wg21.link/p1389r1 SG20 Education and Recommended Videos for Teaching C++ https://www.cjdb.com.au/sg20-and-videos -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.193.76.216 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1605336741.A.923.html ※ 編輯: loveme00835 (123.193.76.216 臺灣), 11/14/2020 16:20:52
文章代碼(AID): #1VhtwbaZ (C_and_CPP)
文章代碼(AID): #1VhtwbaZ (C_and_CPP)