标签:string实现 sprintf str 长度 tar dex cst ret delete
作业要求
代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstring> class MyString { char *_str; int _len; public: MyString() { _str = new char[100]; _len = 100; } MyString(const char *str) { if (str == NULL) { _str = new char[1]; *_str = ‘\0‘; } else { int _len = strlen(str); _str = new char[_len + sizeof(char)]; strcpy(_str, str); } } ~MyString() { delete[]_str; } char *GetString() { return _str; } //设置字符串 void SetString(const char *str) { delete[]_str; int _len = strlen(str); _str = new char[_len + sizeof(char)]; strcpy(_str, str); } //通过下标取得字符 char GetChar(int index) { if(index<=strlen(_str) && index >= 0) return _str[index]; return 0; } //求字符串长度 unsigned int GetStringLens() { unsigned int index = 0; while (_str[index]) { index++; } return index; } //求数组的长度 unsigned int GetArryLens() { return sizeof(_str) / sizeof(_str[0]); } //批量修改其中的某个字符为其它某个字符 char * MyCharReplace(char dest,char source) { while (*_str!=‘\0‘) { if (*_str == dest) { *_str = source; } *_str++; } return _str; } //在末尾追加字符 void MyAddEnd(char c) { char tmp[] = { c,‘\0‘ }; MyString::MyAddEnd(tmp); }; // 在末尾追加字符串 void MyAddEnd(char *str) { _str = strncat(_str, str, strlen(str) + sizeof(char)); } // 在末尾追加整数 void MyAddEnd(int num) { char tmp[255]={0}; sprintf(tmp,"%d",num); MyString::MyAddEnd(tmp); } //在末尾追加浮点数 void MyAddEnd(double num) { char tmp[255] = { 0 }; sprintf(tmp, "%8.3lf", num); MyString::MyAddEnd(tmp); } //在末尾追加MyString void MyAddEnd() { _str = strncat(_str, _str, strlen(_str) + sizeof(char)); } //从头 弹出一个字符 char PopupHead() { int index = 0; char tmp = _str[index]; while(_str[index]!=0) { _str[index] = _str[index + 1]; index++; } return tmp; } //从末尾弹出一个字符 char PopupEnd() { int index = 0; while (_str[index] != 0) { index++; } char tmp = _str[index-1]; _str[index-1] = 0; return tmp; } }; int main() { MyString demo1("我爱你中国!"); //MyString demo2(); MyString demo("I Love Mark"); demo.SetString("i love HaoZaiYi"); std::cout << demo.GetString() << " "<<demo.GetChar(10) << std::endl; std::cout << demo.GetStringLens() << " " << demo.GetArryLens() << std::endl; demo.MyAddEnd(‘y‘); std::cout << demo.GetString() << std::endl; demo.MyAddEnd("aaaaa"); std::cout << demo.GetString() << std::endl; demo.MyAddEnd(123456); std::cout << demo.GetString() << std::endl; demo.MyAddEnd(123456.789); std::cout << demo.GetArryLens() << std::endl; std::cout << demo.PopupHead() << demo.PopupEnd() << std::endl; std::cout << demo.PopupHead() << demo.PopupEnd() << std::endl; std::cout << demo.PopupHead() << demo.PopupEnd() << std::endl; std::cout << demo.PopupHead() << demo.PopupEnd() << std::endl; std::cout << demo.MyCharReplace(‘o‘,‘@‘) << " "<< demo.GetString() << std::endl; return 0; }
高亮部分,代码没有达到作业要求。有bug待解决。
标签:string实现 sprintf str 长度 tar dex cst ret delete
原文地址:http://www.cnblogs.com/bing-z/p/6218580.html