字符串---C++

本文介绍了C++中的字符串概念,包括字符串长度、字符串常量、字符串结束符、字符串变量的表示方式,以及C++中std::string类型的使用。特别讨论了连续输入字符串和读取一行字符串时的注意事项。
摘要由CSDN通过智能技术生成

字符串:

字符串长度
字符串包含的字符个数(不是指中文)。
空字符串的长度是0
“”是空字符串常量,没有一个字符,长度是0
“ ”是空格字符串常量,包含1个空格,长度是1

“boy” 的字符串长度是 3
“大宝贝” 的字符串长度不是3 ,是6或9
(在某些编码中,一个汉字占用2个直接,有些编码中占3个字节)

“” 的字符串长度是0(空串)
“ ” 的字符串长度是1(含有一个空格)

字符串常量

“字面型”字符串常量,要求用“”扩起来。

字符串结束符

在C语言中 每个字符串都会有一个字符串结束符’\0’(占一个字节);
表示这个字符串的结尾, 可以不用自己输入编译器自动会加上,需要留一个字节的内存存放

C++根据编译器实际储存可能有字符串结束符,也可能没有.

字符串变量的表示

在C语言中,使用char类型的数组,来存储字符串变量
注:C语言中,没有专用的字符串类型。
//需要标注内存大小,由于过于麻烦所以C++有了string类型.

在C++中,使用std::string类型来表示字符串变量。

字符串的定义;

#include<string> //C++字符串的头文件

//定义了字符串变量 Friendl,此时是一个空串`
std::string Friendl;
可以使用using namespace std;省略输入std::

#include<iostream>
#include<string>
#include<Windows.h>

using namespace std;

void definition(void){
   
	//定义了字符串变量 girlFriend1,空串
	string girlFriend1;

	//把字符串常量"小犹太"拷贝到girlFriend1
	girlFriend1="小犹太"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值