CString中找關鍵字的技巧

  1. CString中找關鍵字的技巧
    1. CString技法
      1. abcdefghijklmnopqrstuvwxyz 字串搜尋
      2. Find()函數
      3. 找fg左全部
      4. 找fg左3位
      5. 取出特定字之間的字
      6. 找fg右全部
      7. 找fg右3位
      8. Find()注意事項

CString中找關鍵字的技巧

原文連結: https://darkblack01.blogspot.com/2013/04/mfc.html
移植時的最後更新日期: 2015-06-08T09:17:33.507+08:00

我們常常要在字串截取一段之後,尋找想要的一邊、一段、一個字。
在此,將使用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()); //感謝網友jordan5441更正
     abcdefghijk…
    0123456789…


  • 找fg右全部

  • CString sample = “abcdefghijklmnopqrstuvwxyz”;
    const CString goal(“fg”);
    int goalIndex = sample.Find(goal);

    CString result
    = sample.Right( sample.GetLength() - goalIndex+goal.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: -1
    emptyIndex: 0

    搜尋空字串和找不到是兩件事。
    也就是關鍵字搜尋(假設「找某關鍵字」為true)
    「找某關鍵字or空字串」→true
    「找某關鍵字and找不到」→false