标签: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; }
C++【String类】String查找单个字符,查找字符串的函数实现
标签:c++ string类 string查找单个字符 查找字符串的函数实现
原文地址:http://10740184.blog.51cto.com/10730184/1738995