1. 程式人生 > >C++【String類】String查詢單個字元,查詢字串的函式實現

C++【String類】String查詢單個字元,查詢字串的函式實現

#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;

class String
{
public:
    String(const char* str)
        :_str(new char[strlen(str) + 1])
    {
        _size = strlen(str);
        _capacity = _size + 1;
        strcpy(_str, str);
    }

    String(const String& s)
        :_str(NULL)
    {
        String tmp(s._str);
        swap(_str, tmp._str);
    }

    ~String()
    {
        if (_str)
        {
            delete[] _str;
            _size = 0;
            _capacity = 0;
            _str = NULL;
        }
    }
    
     //找單個字元
    /*int Find(char ch)
    {
        for (int i = 0; i < _size;i++)
        {
            if (_str[i] == ch)
            {
                return i;
            }
        }
        return -1;
    }*/
    
    //找字串
    int Find(const char* sub)
    {
        int subSize = strlen(sub);
        int subIndex = 0;
        int srcIndex = 0;
        while (srcIndex < _size - subSize)
        {
            int begin = srcIndex;
            int subIndex = 0;
            while (subIndex < subSize
                && begin < _size
                && _str[begin] == sub[subIndex])
            {
                begin++;
                subIndex++;
            }
            if (subSize == subIndex)
            {
                return srcIndex;
            }
            srcIndex++;
        }
        return -1;
    }
    
private:
    char* _str;
    int _size;
    int _capacity;
};                  

//找單個字元的測試函式
//void Test()
//{
//    String s("abcdef");
//    int ret = s.Find('d');
//    cout << "ret = "<< ret<<endl;
//}

//找字串的測試函式
void Test()
{
    String s("abcdefgh");
    int ret = s.Find("efg");
    cout << "ret=" << ret;
}

int main()
{
    Test();
    system("pause");
    return 0;
}