C++ 字符串处理

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string str("1 2 3 4 5 6 7 8");
char ch[] = "abcdefgh";
string a;
string str_1(ch);
string str_2(str, 2, 5);
string str_3(ch, 5);
string str_4(5,‘X‘);
string str_5(str.begin(), str.end());
cout<<"输出数字序列"<<endl;
cout<<str<<endl;
cout<<"输出字符序列"<<endl;
cout<<ch<<endl;
cout<<a<<endl;

cout<<str_1<<endl;
cout<<str_2<<endl;
cout<<str_3<<endl;
cout<<str_4<<endl;
cout<<str_5<<endl;
return 0;

}



==========================================================

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
int size = 0;
int length = 0;
unsigned long maxsize = 0;
int capacity = 0;
string str("12345678");
string str_custom;
//预分配存储大小
str_custom.reserve(5);
str_custom = str;

//求字符的个数
size = str_custom.size();
length = str_custom.length();

//字符的最大的容量
maxsize = str_custom.max_size();


//从新分配内存之前能够得到的最大内存容量
capacity = str_custom.capacity();
cout<<"size = "<<size<<endl;
cout<<"length = "<<length<<endl;
cout<<"maxsize = "<<maxsize<<endl;
cout<<"capacity = "<<capacity<<endl;
return 0;
}

========================================================

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string cS("conststring");
string s("abcde");
char temp = 0;
char temp_1 = 0;
char temp_2 = 0;
char temp_3 = 0;
char temp_4 = 0;
char temp_5 = 0;
temp =s[2];
temp_1 = s.at(2);
temp_2 = cS[cS.length()];
cout<<temp_1<<endl;
cout<<temp_2<<endl;

return 0;
}

=========================================================


比较

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string A("aBcdef");
string B("AbcdEf");
string C("123456");
string D("123dfg");
int m = A.compare(B);
int n = A.compare(1, 5, B);
int p = A.compare(1, 5, B, 4, 2);
int q = C.compare(0, 3, D, 0, 3);
cout<<"m="<<m<<", n="<<n<<", p="<<p<<", q=" <<q<<endl;
return 0;
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。