C++-计算字符串中某个字符的数量、替换某个字符、提取某⼀
段字符
计算字符数量:
计算字符数量这个很简单,⽹上也有很多⽅法,这⾥只是简单记录
⽅法:
int markNumber = count(str.begin(), d(), 'A');
替换某个字符:
⽅法:
string str = "ABCDEAAA";
string Character = "A";
string replaceCharacter = "Q";
int markNumber = count(str.begin(), d(), 'A');//计算字符数量
cout << "A的数量为:" << markNumber << endl;
cout << "替换前:" << str << endl;
int pos = -1;
pos = str.find(Character);
while (-1 != pos)
{
pos = str.find(Character);
}
cout << "替换后:" << str << endl;
结果:
查某⼀段字符:
⽅法:
std::string str = "ABCD_EAAA";
std::string underLine = "_";
std::cout << "查前:" << str << std::endl;
int pos = -1;
pos = str.find(underLine);
std::string firstHalfCharacter = str.substr(0,pos);//注意:这⾥的0表⽰从第⼏个字符开始,pos表⽰往后⼏位
字符串截取几个字符std::string secondHalfCharacter = str.substr(pos+1,str.length());
std::cout << "符号前的值:" << firstHalfCharacter << std::endl;//输出值为"ABCD"
std::cout << "符号后的值:" << secondHalfCharacter << std::endl;//输出值为"EAAA"
std::string str1 = "ABCDEFG";
int pos1 = -1;
pos1 = str1.find('C');
int pos2 = -1;
pos2 = str1.find('F');
std::string character = str1.substr(pos1,pos2-pos1);
std::cout << "中间某⼀段字符值:" << character << std::endl;//输出值为"CDE"

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。