Re: [問題] 將.txt檔 讀入後要怎麼篩選要的資料?
※ 引述《junny0204 (~睿~)》之銘言:
: 舉個例子來說...
: 我有一個 .txt 檔案
: 裡面的內容為
: aabfghfghfhfhghfgjdj
: abafgjfgjfgjfgjfgjfe
: abbklhfhfhdfhhroryor
: aabqeprtpeteptpedmfd
: aabeererpedpfgpdfgpd
: abbrrrtrterterkhjkhj
: 我要讀取每一列的前三個字母 為 aab的
: 就把該列全部抓起來
: 所以輸出後 新的.txt
: 就是為
: aabfghfghfhfhghfgjdj
: aabqeprtpeteptpedmfd
: aabeererpedpfgpdfgpd
解法一
假設讀字串沒問題, 那麼可以用簡單的敘述來比較前綴字元:
if( 'a' == str[0] && 'a' == str[1] && 'b' == str[2] )
// do something
解法二
想省篇幅就可以用 strstr(字串A,字串B) 在 字串A 裡面找尋
字串B 的起始位址.
在你的問題裡, 即是輸出:
for 字串 s, 使得 strstr(s,"aab") 回傳值為 s 本身
解法三
不過我覺得既然 aab 這串字都已經是編譯前就知道的資訊, 沒有
道理把判斷(字串長度)擺在執行時才作. 也就是說如果我要找
hello 開頭的字串, 編譯器就要生出和下面等價的程式碼:
if( 'h' == str[0] && 'e' == str[1] && 'l' == str[2]
&& 'l' == str[3] && 'o' == str[4] )
// do something
在上面的程式碼中, 我們需要能夠把 c == str[i] 這種型式的程
式碼作重複展開, 剛好 C++11 裡的新 feature:
Varadic Template 可以幫我們達到這個功能, 只要使用:
(c == str[i])...
就可以產生以逗點分隔的敘述清單, 要將這些敘述全都 and 起來
我們需要一個 helper function and_all():
template < typename First, typename... Args >
inline bool and_all( First first, Args... args ) {
return first && and_all( args... );
}
and_all( (c == str[i])... );
要能夠用 ... 展開, 藍色反白部份必須含有 parameter pack, 為
了展開像前面提到的型式:
c 需為 parameter pack, 包裝 'h' 'e' 'l' 'l' 'o'
i 需為 parameter pack, 包裝 0 1 2 3 4
包裝模板引數 利於函式作推導 最常用就是類似下面的方法:
N3493 Compile-time integer sequences(C++14)
網址: http://ppt.cc/8O04
為此我們需要兩個類別模板:
template < char... Chars >
struct char_list { };
template < int... Ints >
struct int_list { };
如此一來 Varadic Template function 可以透過傳進來的 list
型態幫我們推導出需要的 parameter pack:
template < char... Chars, int... Ints >
void print_impl( char const * str,
char_list< Chars... >,
int_list< Ints... > ) {
if( and_all( (str[Ints] == Chars)... ) )
std::cout << str << std::endl;
}
// 印出 aabfghfghfhfhghfgjdj
print_impl( "aabfghfghfhfhghfgjdj",
char_list<'a','a','b'>(),
int_list < 0, 1, 2 >() );
print_impl() 第三個引數基本上是相依於 char_list 的, 也可以
透過 helper class 幫我們產生:
template < int N, int... Ints >
struct make_int_list_impl : make_int_list_impl< N-1, N-1, Ints... >
{ };
template < int... Ints >
struct make_int_list_impl< 0, Ints... > {
using type = int_list< Ints... >;
};
std::is_same<
make_int_list_impl< 5 >::type
, int_list< 0, 1, 2, 3, 4 >
>::value // true
主要的概念就是每次遞迴都在前面增加一個 non-type argument,
最後當 counter N 為 0 的時候在偏特化的模板作收尾.
完整範例: http://ideone.com/hnkOnr
--
≡≡≡≡╔═══╗╔═══╗ ◎ ╔═╗═╗╔═══╗╔═══╗╔╦═╦╗≡≡≡≡
≡金栽經║ ╔╗ ║║ ╔╗ ║╔╗║ ║ ║║ ═ ║║ ╔╗ ║║║ ║║RAINNOUS
≡≡≡≡║ ╚╝ ║║ ╚╝ ║║║║ ║║ ╞╣║ ║║ ║║ ║≡≡≡≡
≡≡≡≡║ ═╣║ ╥ ║║║║ ║ ║║ ═ ║║ ╚╝ ║║ ║ ║≡≡≡≡
≡高佑麗╚═╩═╝╚═╩═╝╚╝╚═╚═╝╚═══╝╚═══╝╚═╩═╝鄭允慧≡
≡≡≡≡≡趙賢榮≡≡≡金智淑≡≡≡RAINBOW≡≡≡盧 乙≡≡≡吳勝雅≡ψmocki
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.121.221.215
※ 編輯: loveme00835 來自: 140.121.221.215 (05/05 02:44)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):