问题描述:
自定义一个CString类,包括获取字符串长度,字符串查找,字符串比较,字符串取子串等都自己来实现。
参考代码:
MyString.h文件
#pragma once
#include <iostream>
#include <assert.h>
#include <stdarg.h>
class CMyString
{
friend std::ostream& operator<< (std::ostream&os, CMyString& other);//重载输入
friend std::istream& operator>> (std::istream&in, CMyString& other);//重载输出
public:
CMyString(const char* str = NULL);//构造函数兼容默认构造函数
CMyString(const CMyString& other);//拷贝构造函数
CMyString& operator=(const CMyString& other);//重载=
CMyString operator+(const CMyString& other);//重载+
CMyString operator+=(const CMyString& other);//重载+=
~CMyString();//析构函数
size_t GetLength();//获取字符串长度
bool operator==(const CMyString& other);//判断两个字符串是否相等
char& operator[](unsigned int nIndex);//重载[]
const char* GetC_Str() const;//获取C字符串
void MakeUpper();//转为大写
void MakeLower();//转为小写
bool IsEmpty();//判断字符串是否为空
void Empty();//清空字符串
void Format(char* fmt, ...);//格式化字符串
int CompareNoCase(const CMyString& other);//不区分大小写比较字符串,大于other返回1,小于返回-1,等于返回0
int CompareNoCase(const char* str);//重载不区分大小写的比较函数
CMyString LeftSubString(int nCount);//取子串,从左边开始取nCount个字符
CMyString RightSubString(int nCount);//取子串,从右边往左边数nCount个字符
CMyString MidSubString(int nFirst, int nCount);//取子串,从nFirst的位置开始,取nCount个字符
CMyString MidSubString(int nFirst);//重载取子串,从nFirst的位置开始,一直取到最后
int FindString(const CMyString& other);//查找子串
int FindString(const char* str);//重载查找子串
int FindString(const CMyString& other, int nStart);//从nStart位置开始查找子串
int FindString(const char* str, int nStart);//重载从nStart位置开始查找子串
int FindChar(char ch);//查找字符
int FindChar(char ch, int nStart);//从nStart的位置开始查找字符
void MakeReverse();//字符串逆置
int Remove(char ch);//删除字符串中所有的指定字符
int Replace(char chOld, char chNew);//替换字符
int Replace(char* pOld, char* pNew);//替换字符串
int Insert(int nIndex, char ch);//在nIndex位置插入一个字符
int Insert(int nIndex, char* pStr);//在nIndex位置插入一个字符串
void Sort();//对字符串进行排序
int ToInt();//把字符串转成int类型
private:
size_t MyStrlen(const char *pStr);
char * MyStrcpy(char *dst, const char *src);
char * MyStrcat(char *dst, const char *src);
int MyStrcmp(const char* str1, const char* str2);
char *ReturnUpper(const char* str);
char *ReturnLower(const char* str);
char* GetSubstring(const char *strSource, const unsigned int uStartPos, const unsigned int uEndPos);
int MyStrstr(const char *s1, const char *s2, int nStartPos = 0);
int MyIsSpace(char ch);
int MyIsDigit(char ch);
int MyAtoi(const char* pStr);
private:
char *m_str;
size_t m_nLength;
};
MyString.cpp文件
#include "StdAfx.h"
#include "MyString.h"
CMyString::CMyString(const char* str /*= NULL*/)
{
if (NULL == str)
{
m_nLength = 0;
m_str = new char[1];
*m_str = '\0';
}
else
{
m_nLength = MyStrlen(str);
m_str = new char[m_nLength + 1];