c++不支持真正意义的字符串,C语言中用字符数组和一组函数实现字符串操作,C语言不支持自定义类型,因此无法获得字符串类型。
从c到c++的进化过程引入了自定义类型,在c++中可以通过类完成字符串类型的定义。
c++语言中没有原生的字符串类型,但是c++标准库提供了string类型,string直接指出字符串连接,字符串大小比较,子串查找和提取,字符串的插入和替换。
#include <iostream>
#include <string>
using namespace std;
void string_sort(string a[], int len)
{
for(int i=0; i<len; i++)
{
for(int j=i; j<len; j++)
{
if( a[i] > a[j] )
{
swap(a[i], a[j]);
}
}
}
}
string string_add(string a[], int len)
{
string ret = "";
for(int i=0; i<len; i++)
{
ret += a[i] + "; ";
}
return ret;
}
int main()
{
string sa[7] =
{
"Hello World",
"D.T.Software",
"C#",
"Java",
"C++",
"Python",
"TypeScript"
};
string_sort(sa, 7);
for(int i=0; i<7; i++)
{
cout << sa[i] << endl;
}
cout << endl;
cout << string_add(sa, 7) << endl;
return 0;
}
字符串与数字的转换:
标准库中提供了相关的类对字符串和数字进行转换。
字符串流类(sstrem)用于string的转换
<sstream> -相关头文件
istringstream -字符串输入流
ostringstream-字符串输出流、
使用方法:
string->数字
istringstresam iss(“123.45"); // 字符串流
double num;
iss>>num;
数字 ->string
ostringstream oss; //字符串输出流对象
oss<<543.21;
string s=oss.str();
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str()) //强制类型转换ostream->ostringstream
int main()
{
double n = 0;
if( TO_NUMBER("234.567", n) )
{
cout << n << endl;
}
string s = TO_STRING(12345);
cout << s << endl;
return 0;
}
问题:字符串循环右移
abcdefg 循环右移3位后得到 efgabcd?
// abcd. efg==>3 efg abcd
//abc==>3- abc==>1 cab
#include <iostream>
#include <string>
using namespace std;
string operator >> (const string& s, unsigned int n)
{
string ret = "";
unsigned int pos = 0;
n = n % s.length();pos = s.length() - n;
ret = s.substr(pos); // 提取子串,从pos开始
ret += s.substr(0, pos);
return ret;}
int main(){
string s = "abcdefg";
string r = (s >> 3);
cout << r << endl;
return 0;
}
// abcdefg==>8
//abcdefg==>1
//8%7 ==>1
// 7-1==>6
//abcdef g
//ret==>g
//ret=g+abcdef
//ret=gabcdef