/******************************定义为 string 类型******************************/
6.string 类型变量的赋值:
①直接赋值 str1 = str2;
②使用assign 函数:可以取第二个字符串的任意字符给字符串一
stringstr1 = “abcd”;
stringstr2 = “efg”;
str2.assign(str1,1, 3); //(字符串名,起始元素,赋值个数)
out: str1:abcd
str2:bcd
※string类型可自动调整字符串大小
7.string类型字符串全部合并
str1+ str2;
char 类型字符数组要使用 strcat 函数实现合并
strcat 函数将字符串2合并给字符串1,因此1要能放下两个字符串
8.string 类型字符串部分合并
使用 append 函数
str1= “abcd”;
str2= “efg”;
str1.append(str2,0, 2); //(字符串名,起始位置,合并个数)
out: str1:abcdef
str2:efg
char 类型字符数组的部分合并要使用 strncat 函数
char ch1[] = “abcd”;
char ch2[] = “efg”;
strncat(ch1, ch2, 2); //(被合并数组名,合并数组名,合并个数)
out: ch1: abcdef
ch2:efg
※只能从首位置开始向后合并
9.string 型字符串的替换
使用 replace 函数
stringstr1 = “gh”;
stringstr2 = “abcdef”;
str1.replace(0,1,str2,4,2);
//(被替换原始位置,替换个数,替换字符串名,替换位置,替换个数)
out: str1:efh
str2: abcdef
※replace 函数支持 char 类型字符数组
char 类型字符数组的替换要使用 strncpy 函数
char ch1[10] = “gh”;
char ch2[] = “abcdef”;
strncpy(ch1, ch2, 3);//(被替换字符数组名,替换字符数组名,替换个数)
out: ch1: abc
ch2: abcdef
※只能从首位置开始替换与被替换
10.string 型字符串的复制
①string 类型之间复制使用 assign 函数
②string 到char 类型复制使用 copy 函数
stringstr = “abcd”;
charch[] = “1234”;
intn;
cout<< "源字符串"<< ch << endl;
n= str.copy(ch, 4, 0);//(复制数组名,被复制元素个数,被复制元素起始位置)
cout<<"复制了:"<< n << “字符” << endl;
cout<<"复制后:"<< ch<< endl;
out: 源字符串:1234
复制了4字符
复制后:abcd
※所有操作针对于string类型,且返回值为复制字符个数
char 类型使用 memmove 函数进行字符串复制
char ch1[15] = “abcdefghijklmn”;
char ch2[] = “1234567890”;
cout << “源字符串:” << ch1 << endl;
memmove(ch1, ch2, 10);//(被复制字符串,复制字符串,复制的字符数目)
cout << “拷贝后:” << ch1 << endl;
out: 源字符串:abcdefghijklmn
拷贝后:1234567890klmn
11.string 类型字符串的插入
使用insert 函数
定义格式 str.insert(index1, str1, index2, num );
(被插入位置,插入字符串名,插入位置,插入个数)
stringstr1 = “12789”;
stringstr2 = “3456”;
str1.insert(2,str2, 0, 4);
out: 123456789
12.string 类型字符串的删除
使用 erase 函数
#include <iostream>
#include <string.h>
using namespace std;
int main (void)
{
strings ( "give me");
cout<< "原始字符串:" << s << endl;
s.erase(2,2);
cout<< "现在字符串为:" << s << endl;
s.erase(2);
cout<< "现在字符串为:" << s << endl;
s.erase();
cout<< "现在字符串为:" << s << endl;
return0;
}
Out: 原始字符串:give me
现在字符串为:gi me
现在字符串为:gi
现在字符串为:
※erase() 函数可以根据字符串中指定的位置删除字符,同时返回指向下一个字符this指针