原文來自CString中找關鍵字的技巧-《Darkblack》
我們常常要在字串截取一段之後,尋找想要的一邊、一段、一個字。
在此,將使用MFC的CString做示範。(因為這個我最常用!XD)
CString技法
abcdefghijklmnopqrstuvwxyz
字串搜尋
Find()函數
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString goal(“fg”);
int goalIndex = sample.Find(goal);
abcdefghijk…0123456789…
找fg左全部
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString goal(“fg”);
int goalIndex = sample.Find(goal);
CString result = sample.Left(goalIndex);
abcdefghijk…0123456789…
找fg左3位
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString goal(“fg”);
int goalIndex = sample.Find(goal);
const int charAmount = 3;
CString result = sample.Mid(goalIndex-charAmount, charAmount);
abcdefghijk…0123456789…
取出特定字之間的字
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString begin(“bc”), end(“fg”);
int beginIndex = sample.Find(begin);
int endIndex = sample.Find(end);
CString result
= sample.Mid(beginIndex+begin.GetLength(),
endIndex-beginIndex+begin.GetLength());
abcdefghijk…0123456789…
找fg右全部
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString goal(“fg”);
int goalIndex = sample.Find(goal);
CString result
= sample.Right( sample.GetLength() - goalIndex+goalIndex.GetLength() );
abcdefghijk…0123456789…
找fg右3位
CString sample = “abcdefghijklmnopqrstuvwxyz”;
const CString goal(“fg”);
int goalIndex = sample.Find(goal);
const int charAmount = 3;
CString result = sample.Mid(abcIndex+goalIndex.GetLength(), charAmount);
abcdefghijk…0123456789…
Find()注意事項
CString sample = “abcdefghijklmnopqrstuvwxyz”;
int errorIndex = sample.Find(“llllll”);
int emptyIndex = sample.Find(“”);
errorIndex: -1emptyIndex: 0
搜尋空字串和找不到是兩件事。
也就是關鍵字搜尋(假設「找某關鍵字」為true)
「找某關鍵字or空字串」→true
「找某關鍵字and找不到」→false
沒有留言:
張貼留言