C++ string

本文详细介绍了C++中字符串的各种操作,包括构造函数、赋值、连接、获取特定字符、赋新值、在末尾添加文本、迭代器使用、删除字符、清空字符串、检查是否为空、转换为C字符数组、复制到字符数组、长度和容量、最大可能长度、交换内容、查找字符、子字符串提取、按索引访问字符、内容比较以及内存比较。通过实例展示了每个函数的功能和用法,帮助读者深入理解C++字符串处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String

string::string() 功能:构造函数,用于字符串初始化
#include<iostream>
#include<string>

using namespace std;

int main(){
   //string::string() 功能:构造函数,用于字符串初始化 
   string s1;
   string s2("mozhenhai string");
   string s3(s2);
   string s4(s2,8);
   string s5(10,'m');
   string s6a(10,42);
   string s6b(s2.c_str(),s2.c_str()+4);
   cout<<s1<<endl;
   cout<<s2<<endl;
   cout<<s3<<endl;
   cout<<s4<<endl;
   cout<<s5<<endl;
   cout<<s6a<<endl;
   cout<<s6b<<endl;
} 

运行结果


mozhenhai string
mozhenhai string
i string
mmmmmmmmmm
**********
mozh
string::operator+=()函数 功能:连接两个字符串
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::operator+=()函数 功能:连接两个字符串
	string first("tomy");
	string second("may");
	first+=" is a boy ";
	second+=" is a girl";
	cout<<first<<endl;
	cout<<first<<endl;
	first+=second;
	cout<<first<<endl;

} 

运行结果

tomy is a boy
tomy is a boy
tomy is a boy may is a girl
string::operator=()函数 功能:字符串赋值
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::operator=()函数 功能:字符串赋值
	string str1="Test string " ;
	string str2("code");
	string str3("mo");
	
	str1+=str2;
	cout<<str1<<endl;
	str1+=str3;
	cout<<str1<<endl;
    //string::operator[]()函数 功能:获取特定的字符
	string str("test string");
	for(int i=0;i<str.size();i++){
		cout<<str[i]<<" ";
	}

} 

运行结果

Test string code
Test string codemo
t e s t   s t r i n g
string::operator[] () 功能:获取特定的字符
#include<iostream>
#include<string>

using namespace std;

int main(){
   //string::operator[]() 功能:获取特定的字符
   string str("mozhenhai");
   for(int i=0;i<str.length();i++){
   	cout<<str[i]<<" ";
   } 
   
} 

运行结果

m o z h e n h a i
string::assign()函数 功能:为字符串赋新值
#include<iostream>
#include<string>

using namespace std;

int main(){
	//string::assign()函数 功能:为字符串赋新值
	string str;
	string base="mozhenhai is wrinting#code";
	//used in the smae order as described above
	str.assign(base);
	    cout<<str<<endl;
	str.assign(base,9,12);
    	cout<<str<<endl;	
	str.assign("program is the tool",7);
		cout<<str<<endl;
	str.assign("I like coding");
		cout<<str<<endl;
	str.assign(3,'?');
		cout<<str<<endl;
	str.assign<int>(3,0x2F);
		cout<<str<<endl; 
	str.assign(base.begin()+2,base.end()-4);
	    cout<<str<<endl;
} 

运行结果

mozhenhai is wrinting#code
 is wrinting
program
I like coding
???
///
zhenhai is wrinting#

string::append()函数 功能:在字符串的末尾添加文本
#include<iostream>
#include<string>

using namespace std;

int main(){
	//string::append()函数 功能:在字符串的末尾添加文本 
	string str;
	string str2="mozhenhai";
	string str3="you#are#a#bad#boy";
	//used in the same order as described above
	str.append(str2);
	cout<<str<<endl;
	str.append(str3,3,6);//第四个个字符后面六个字符包括第四个 
	cout<<str<<endl;
	str.append("boy",2);
	cout<<str<<endl;
	str.append("good:");
	cout<<str<<endl;
	str.append(6,'!');
	cout<<str<<endl;
	str.append(str3.begin()+4,str3.end());
	cout<<str<<endl;
	str.append<int>(6,0x2E);//"......"
	cout<<str<<endl;
} 

运行结果

mozhenhai
mozhenhai#are#a
mozhenhai#are#abo
mozhenhai#are#abogood:
mozhenhai#are#abogood:!!!!!!
mozhenhai#are#abogood:!!!!!!are#a#bad#boy
mozhenhai#are#abogood:!!!!!!are#a#bad#boy......

string::begin()函数 功能:返回一个迭代器;指向第一个字符
string::end()函数 功能:返回一个迭代器;指向字符串的末尾。(最后一个字符的下一个位置)
#include<iostream>
#include<string>

using namespace std;

int main(){
	 //string::begin()函数 功能:返回一个迭代器;指向第一个字符
    //string::end()函数  功能:返回一个迭代器;指向字符串的末尾。(最后一个字符的下一个位置)
	 
	string str("program");
	string::iterator it;
	for(it=str.begin();it<str.end();it++){
		cout<<" "<<*it;
		
	} 
} 

运行结果

 p r o g r a m
string::rbegin()函数 功能:返回一个逆向迭代器,指向最后一个字符
string::rend()函数 功能:返回一个逆向迭代器,指向第一个元素的前一个位置
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main(){
   //string::rbegin()函数 功能:返回一个逆向迭代器,指向最后一个字符
   //string::rend()函数 功能:返回一个逆向迭代器,指向第一个元素的前一个位置
   string str("mozhenhai is coding");
   string::reverse_iterator rit;
   for(rit=str.rbegin();rit!=str.rend();rit++){
   	cout<<*rit;
   } 
   cout<<endl;
   
} 

运行结果

gnidoc si iahnehzom

string::push_back() 功能:Append character to string待完善
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main(){
   //string::push_back() 功能:Append character to string
   string str;
   ifstream file("test.txt",ios::in);
   while(!file.eof()){
   	str.push_back(file.get());
   }
   cout<<str;

   
} 

test.txt 的内容

You are coder.The code is art.
Coding is cool.

运行结果

You are coder.The code is art.
Coding is cool.
string::insert()函数 功能:插入字符
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::insert()函数 功能:插入字符
	string str1="you are a lovely boy";
	string str2="not ";
	string str3("is intelligent girl");
	
	string::iterator it;
	
//	used in the same order as described above
    str1.insert(8,str2);
    cout<<str1<<endl;
    str1.insert(14,str3,3,11);
    cout<<str1<<endl;
    str1.insert(14,"code is intersting ",5);
    cout<<str1<<endl;
    str1.insert(14,"code is intersting ");
    cout<<str1<<endl;
    str1.insert(14,2,',');
    cout<<str1<<endl;
    str1.insert(str1.begin()+3,'#');
    cout<<str1<<endl;
	str1.insert(str1.end(),4,'!');
	cout<<str1<<endl;
	it=str1.insert(str1.begin()+3,'$');
	cout<<str1<<endl;
	str1.insert(it+2,str3.begin(),str3.begin()+2);
	cout<<str1<<endl;

} 

运行结果

you are not a lovely boy
you are not a intelligentlovely boy
you are not a code intelligentlovely boy
you are not a code is intersting code intelligentlovely boy
you are not a ,,code is intersting code intelligentlovely boy
you# are not a ,,code is intersting code intelligentlovely boy
you# are not a ,,code is intersting code intelligentlovely boy!!!!
you$# are not a ,,code is intersting code intelligentlovely boy!!!!
you$#is are not a ,,code is intersting code intelligentlovely boy!!!!

string::erase()函数 功能:删除字符
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::erase()函数 功能:删除字符
	string str("you are a lovely boy");
	string::iterator it;
	//erase used in the same order as described above:
	str.erase(14);//删除下标为14(第十五个字符)及以后的字符 
	cout<<str<<endl;
	str.erase(5,2);//删除下标为5及后面一个字符。就是连同下标为5的两个字符 
	cout<<str<<endl;

} 

运行结果

you are a love
you a a love

string::clear()函数 功能:Clear string
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::clear()函数 功能:Clear string
    string str("tomy");
    cout<<str<<endl;
	str.clear();
	cout<<"after str.clear:"<<str<<endl;
	char c;
	cout<<"please type some lines of text.Enter a period to finsh:\n"<<endl;
	do{
		c=cin.get();
		str+=c;
		if(c=='\n'){
			cout<<str<<endl;
			str.clear();
			
		}
	}while(c!='.');
	cout<<"after str.clear:"<<str;//str 为 . 
} 

运行结果

tomy
after str.clear:
please type some lines of text.Enter a period to finsh:

hello world.
after str.clear:hello world.
string::empty()函数 功能:如果字符串为空,返回真
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::empty()函数 功能:如果字符串为空,返回真
	string str1;
	string str2;
	cout<<"please introduce a text,Enter an empty line to finsh:\n"<<endl;
	do{
		getline(cin,str2);
		str1+=str2+'\n';
		 
	}while(!str2.empty());
	cout<<"The text you intorduced was:\n";
	cout<<str1;

} 

运行结果

please introduce a text,Enter an empty line to finsh:

hello world

The text you intorduced was:
hello world


string::c_str()函数 功能:将字符串以C字符数组的形式返回
#include<iostream>
#include<string>
#include<cstring>
#include<fstream>

using namespace std;

int main(){
   //string::c_str()函数 功能:将字符串以C字符数组的形式返回
   char *cstr,*p;
   string str("mo zhen hai is coding program is intersting");
   cstr=new char [str.size()+1];
   strcpy(cstr,str.c_str());
   //cstr now contains a c-string copy of str
   p=strtok(cstr," ");
   while(p!=NULL){
   	cout<<p<<endl;
   	p=strtok(NULL," ");
   }
    delete[] cstr;
} 

运行结果

mo
zhen
hai
is
coding
program
is
intersting

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

运行结果

Splitting string "- This, a sample string." into tokens:
This
a
sample
string
string::copy()函数 功能:将内容复制为一个字符数组
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::copy()函数 功能:将内容复制为一个字符数组
	
	string str("program codecode");
	int length;
	char buffer[20];
	length=str.copy(buffer,6,5);//6,5:5为字符的下标,6为字符串长度 
	buffer[length]='\0';
	
	cout<<"buffer contains: "<<buffer<<endl;
	
	char *array=new char [20];
	array[str.copy(array,4,6)];
	cout<<array<<endl;
	array[str.copy(array,5)];
	cout<<array<<endl;
	delete []array; 

} 

运行结果

buffer contains: am cod
m co
progr

string::length()函数 功能:返回字符串的长度
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::length()函数 功能:返回字符串的长度
	string str("I like program");
	cout<<"The length of str is :"<<str.length()<<"characters"<<endl;

} 

运行结果

The length of str is :14characters
string::size()函数 功能:返回字符串中字符的数量
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::size()函数 功能:返回字符串中字符的数量
	//string::length()函数 功能:返回字符串的长度
	string str("program code");
	cout<<"The size of str is : "<<str.size()<<endl;
	cout<<"The length of str is : "<<str.length()<<endl;
    //string::substr()函数 功能:返回某个子字符串
	string str1("you are program boy");
	string str2=str1.substr(3,4);//3,4 3是下标位置 ,4是长度 
	cout<<str2<<endl; 
} 

运行结果

The size of str is : 12
The length of str is : 12
 are
string::capacity()函数 功能:返回重新分配空间前的字符容量
#include<iostream>
#include<string>

using namespace std;

int main(){
	//string::capacity()函数 功能:返回重新分配空间前的字符容量
	string str("program is");
	cout<<"size "<<str.size()<<endl;
	cout<<"length: "<<str.length()<<endl;
	cout<<"capacity "<<str.capacity()<<endl;
	cout<<"max_size "<<str.max_size()<<endl;
} 

运行结果

size 10
length: 10
capacity 10
max_size 4611686018427387897

string::max_size()函数 功能:返回字符的最大可能个数
#include<iostream>
#include<string>
#include<cstring>
#include<fstream>

using namespace std;

int main(){
   //string::max_size()函数 功能:返回字符的最大可能个数
   string str("mozhenhai");
   cout<<"size: "<<str.size()<<endl;
   cout<<"length: "<<str.length()<<endl;
   cout<<"capacity: "<<str.capacity()<<endl;
   cout<<"max_size: "<<str.max_size()<<endl; 
  
}
   

运行结果

size: 9
length: 9
capacity: 9
max_size: 4611686018427387897
string::swap()函数 功能:交换两个字符串的内容
#include<iostream>
#include<string>

using namespace std;

int main(){
   //string::swap()函数 功能:交换两个字符串的内容
	string buyer("money");
	string seller("goods");
	
	cout<<"before swap buyer:"<<buyer<<endl;
	cout<<"before swap seller:"<<seller<<endl;
	
	seller.swap(buyer);
	 
    cout<<"after swap buyer:"<<buyer<<endl;
	cout<<"after swap seller:"<<seller<<endl;
} 

运行结果

before swap buyer:money
before swap seller:goods
after swap buyer:goods
after swap seller:money

string::find()函数 功能:在字符串中查找字符
#include<iostream>
#include<string>

using namespace std;

int main(){
   //string::find()函数 功能:在字符串中查找字符
    string str("The boy is writing code");
    string strf1("by");
    string strf2("is");
    cout<<string::npos<<endl; 
    cout<<str.find(strf1)<<endl; //返回子字符串在字符串中的起始位置下标 
    size_t found;
    found-str.find(strf2);
    if(found!=string::npos){
    	cout<<strf2<<" at: "<<found<<endl;
	}
} 

运行结果

18446744073709551615
18446744073709551615
is at: 24

string::substr()函数 功能:返回某个子字符串
#include<iostream>
#include<string>
#include<cstring>
#include<fstream>

using namespace std;

int main(){
   //string::substr()函数 功能:返回某个子字符串
   string str="i am coding,what are you doing";
   string str1,str2;
   size_t pos;
   str1=str.substr(5,6);//"coding"
   pos=str.find("you");//get from "you" to the end
   str2=str.substr(pos);
   cout<<str1<<endl;
   cout<<str2<<endl; 
} 

运行结果

coding
you doing

string::at()函数 功能:按给定索引值返回字符
#include<iostream>
#include<string>

using namespace std;

int main(){
		//string::at()函数 功能:按给定索引值返回字符
	string str("mozhenhai");
	for(int i=0;i<str.length();i++){
		cout<<str.at(i)<<endl;
	}
} 

运行结果

m
o
z
h
e
n
h
a
i

#include<iostream>
#include<string>
#include<cstring>
#include<fstream>

using namespace std;

int main(){
   //string::data()函数 功能:返回内容的字符数组形式
   int length;
   string str="mozhenhai";
   char *cstr="mozhenhai";
   if(str.length()==strlen(cstr)){
   	cout<<"str and cstr hava the same length"<<endl;
   	length=str.length();
   	//C 库函数 int memcmp(const void *str1, const void *str2, size_t n))
	// 把存储区 str1 和存储区 str2 的前 n 个字节进行比较。
	/*参数
    str1 -- 指向内存块的指针。
    str2 -- 指向内存块的指针。
    n -- 要被比较的字节数。
    返回值
    如果返回值 < 0,则表示 str1 小于 str2。
    如果返回值 > 0,则表示 str1 大于 str2。
    如果返回值 = 0,则表示 str1 等于 str2。*/
    /*s1,s2为字符串时候memcmp(s1,s2,1)就是比较s1和s2的第一个字节的ascII码值;
    memcmp(s1,s2,n)就是比较s1和s2的前n个字节的ascII码值;

    如:char *s1="abc";
       char *s2="acd";
       int r=memcmp(s1,s2,3);
   就是比较s1和s2的前3个字节,
   第一个字节相等,第二个字节比较中大小已经确定,
   不必继续比较第三字节了所以r=-1.*/
   	if(memcmp(cstr,str.data(),length)==0){
   		cout<<"str and cstr have the same content"<<endl;
	   }
   }
}
   

运行结果

str and cstr hava the same length
str and cstr have the same content
string::compare()函数 功能:比较两个字符串,相等返回0,不相等返回-1
#include<iostream>
#include<string>

using namespace std;

int main(){
    //string::compare()函数 功能:比较两个字符串,相等返回0,不相等返回-1 
	
	string str1("code");
	string str2("programcode");
	string str3("code");
	cout<<str1.compare(str3)<<endl;
	if(str1.compare(str2)){
		cout<<"str1:"<<str1<<endl<<"str2:"<<str2; 
	}
	cout<<str2.compare(7,10,"code")<<endl;
	//7,10表示第八个字符到第十一个字符 
	cout<<str2.size()<<endl;
	
	cout<<str2.compare(str2.size()-4,4,"code")<<endl;
	cout<<str2.compare(7,4,"code")<<endl;
	
	//7,4表示第八个字符后面四个字符包括第八个
	//简单概括就是如果后面数字前面大按照下标截取
	//如果后面数字比前面小或等按照下标加长度
	cout<<str1.compare(2,2,str2,9,10)<<endl;//str1:de str2:de
	cout<<str1.compare(2,2,str2,9,12)<<endl;//str1:de str2:de
	//第二种截取字符串的方法
	//表明超出字符串长度的下标和字符串最大下标效果一样 
} 

运行结果

0
str1:code
str2:programcode0
11
0
0
0
0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值