关于string与cstring的一些总结

cstring类:

memsert

#include <bits/stdc++.h>
using namespace std;
int a[50],b[50];
int main(){
	memset(a,0,sizeof(a));//将整个数组赋值为0
	memset(a,-1,sizeof(a));//将整个数组赋值为-1
    //注意!!只有0和-1才可以用memset赋值,其余的1如memset(a,x,sizeof(a))等用memset赋值数组内均不是x
	return 0;
} 

memcpy

#include <bits/stdc++.h>
using namespace std;
int a[50],b[50];
int main(){
	a[1]=1;
	a[2]=2;
	a[3]=3;
	b[1]=4;
	b[2]=5;
    memcpy(a,b,sizeof(b));//把b数组赋值给a数组
	memcpy(a+1,b+1,8);//把b数组从1开始赋值给a,a也从1开始,8是2个int类型,即a[1]=b[1],a[2]=b[2]
	for (int i=1;i<=5;++i) printf("%d\n",a[i]);
	return 0;
} 

string类

find

#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	printf("%d\n",st.find("123"));//查找123的位置,找不到返回-1
	return 0;
}

substr

#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	string S=st.substr(1,2);//st从1到2的字符串
	cout << S << endl;
	return 0;
}

insert

#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	st.insert(st.begin(),'#');//在头插入'#'
	cout << st << endl;
	return 0;
}

erase

#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	st.erase(st.find('#'),'#');//删除#后的所有元素
	cout << st << "end" << endl;
	return 0;
}

replace

#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	string ss="223";
	st=st.replace(st.find("#"),1,"u");//从第一个#位置替换第一个#为u
	cout << st << endl;
	return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	string ss="224";
	st=st.replace(0,2,ss,ss.find("2"),3);
	//用ss的指定子串(从找到2位置数共3个字符)替换从0到2位置上的line
	cout << st << endl;
	return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main(){
	string st="12345 # $ yyu";
	string ss="221";
	st=st.replace(0,2,ss);
	//用ss替换从指定位置0开始长度为3的字符串
	cout << st << endl;
	return 0;
}

原文链接: https://www.cnblogs.com/zhouykblog/p/9940416.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    关于string与cstring的一些总结

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/284656

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 上午8:05
下一篇 2023年2月15日 上午8:06

相关推荐