17.C++-string字符串类(详解)

C++字符串string类

在C语言里,字符串是用字符数组来表示的,而对于应用层而言,会经常用到字符串,而继续使用字符数组,就使得效率非常低.

所以在C++标准库里,通过类string从新自定义了字符串。

头文件: #include <string>

  • string直接支持字符串连接
  • string直接支持字符串的大小比较
  • string直接支持子串查找和提取
  • string直接支持字符串的插入和替换
  • string同时具备字符串数组的灵活性,可以通过[ ]重载操作符来访问每个字符。

字符串数组和string对象尽量不要混合使用,会带来意想不到的问题

例如,通过字符串数组赋值给string对象:

打印运行:

这是因为,使用for循环拷贝,仅仅改变了str的串内容,并没有改变str的length长度.

 

string类常用的成员函数有:

 

 

  

 

const char* c_str();   

返回一个常量C字符串, 内容与本string串相同. 

注意:当本string的内容改变,或被析构后,返回的字符串也不会被改变,因为返回的字符串是从新通过new char[]出来.

参考下面代码,可以发现返回的C字符串地址和string里的字符串地址完全不同:

 

反转相关(位于头文件<algorithm>)

拷贝相关:

 

"abcdefg" 循环右移3位等到: "efgabcd"

代码如下:

 

代码如下:

  

字符串与数字的转换

以前,在C里,当我们想获取字符串里的数字时,一般都是通过strtoul()或者sscanf()获取

在C++标准库里,也提供字符串与数字的转换.位于<sstream>头文件.

同时需要用到两个类:

将string 字符串 ->数字,使用方法如下

也可以通过临时对象转换,这样写:

或者将第3行,写为宏:

  

将数字->string 字符串,使用方法如下

也可以通过宏,这样写:

  

 


文章来源:https://www.cnblogs.com/lifexy/p/8642163.html

转载于:https://www.cnblogs.com/xiongjim/p/9673918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自己实现的字符串 class CMStringImp; class CMstring { public: explicit CMstring(void); ~CMstring(void); CMstring(LPCTSTR lpszstr); CMstring(const CMstring& lpszstr); CMstring& operator = (const CMstring& lpszstr); operator LPCTSTR() const; bool operator == (const CMstring&) const; bool operator != (const CMstring&) const; bool operator < (const CMstring&) const; TCHAR operator[] (int nIndex) const; TCHAR& operator[] (int nIndex); CMstring& operator += (LPCTSTR pStr); CMstring& operator += (TCHAR ch); friend CMstring operator+(const CMstring& str1, const CMstring& str2); friend CMstring operator+(const CMstring& str1, LPCTSTR lpszstr); friend CMstring operator+(const CMstring& str1, TCHAR ch); friend CMstring operator+(TCHAR ch, const CMstring& str1); friend CMstring operator+(LPCTSTR lpszstr, const CMstring& str1); // friend wostream operator <<(wostream &is;,const CMstring &str;); public: LPCTSTR GetData() const; bool IsEmpty() const; TCHAR GetAt(int) const; TCHAR& GetAt(int); int GetLength() const; int Compare(const CMstring&) const; int CompareNoCase(const CMstring&) const; int Find(TCHAR ch, int nStart = 0) const; int Find(LPCTSTR pStr, int nStart = 0) const; int ReverseFind(TCHAR ch) const; int ReverseFind(LPCTSTR pStr) const; CMstring Right(int nCount) const; CMstring Left(int nCount ) const; public: CMstring& MakeLower(); CMstring& MakeUpper(); CMstring& MakeReverse(); int Replace(TCHAR chOld, TCHAR chNew); int Replace(LPCTSTR pszOld, LPCTSTR pszNew); int Insert(int iIndex, TCHAR ch); void Format(LPCTSTR lpszFormat, ...); private: CMStringImp* m_pImp; };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值