应用开发中大多数都在对字符串进行处理,本节主要介绍2个内容,1个是对C++标准库中的string字符串类的一个使用体验,1个是对C++标准库中的用于字符串和数字之间相互转换的字符串流类sstream类的使用体验。
C语言不支持真正意义上的字符串,故使用字符数组来实现字符串的操作;同样的,C++中也没有对字符串的原生支持,但是C++标准库却提供了string这个字符串类来支持字符串的所有操作。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string stringAdd(string s[], int len)
{
string sRet = "";
for(int i=0; i<len; i++)
{
sRet += s[i] + "; ";
}
return sRet;
}
void stringSort(string s[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if(s[i] > s[j])
{
swap(s[i], s[j]);
}
}
}
}
int main()
{
string sArray[] =
{
"kan",
"wan",
"xu",
"zhang",
"jia",
"le"
};
cout << stringAdd(sArray, 6) << endl;
stringSort(sArray, 6);
for(int i=0; i<6; i++)
{
cout << sArray[i] << endl;;
}
istringstream iss("123.34");
double d;
iss >> d;
cout << d << endl;
ostringstream oss;
int i = 100;
oss << i;
string s = oss.str();
cout << s << endl;
return 0;
}
输出结果如下: