---- 整理自狄泰软件唐佐林老师课程
C语言 不支持真正意义上的字符串
C语言用 字符数组 和 一组函数 实现字符串操作
C语言 不支持自定义类型,因此无法获得字符串类型
C++语言直接支持C语言的所有概念
C++语言中 没有 原生的字符串类型
#include
#include using namespace std;void string_sort(string a[], int len)
{for(int i=0; ifor(int j=i; jif( a[i] > a[j] ){swap(a[i], a[j]);}}}
}string string_add(string a[], int len)
{string ret = "";for(int i=0; iret += 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;
}

标准库中提供了相关的类对字符串和数字进行转换
字符串流(sstream)用于string的转换
相关头文件使用方法:
string ==> 数字

数字 ==> string

#include
#include
#include using namespace std;#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())int main()
{double n = 0;if( TO_NUMBER("234.567", n) ){cout << n << endl; }string s = TO_STRING(12345);cout << s << endl; return 0;
}

注:我们来分析一下上面两个宏定义:
#define TO_NUMBER(s, n) (istringstream(s) >> n)
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())
他们的特别之处就在于:直接调用构造函数而产生了一个临时对象,临时对象的生命周期只有一条语句,利用临时对象把想要的变量输入或输出。(ostringstream() << n) 这条语句得出的结果类型返回basic_ostream类对象,它应该是ostringstream的父类,它可能没有str成员函数,所以要类型转换为子类对象,所以强制类型转换成 ostringstream& 。

#include
#include 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);ret += s.substr(0, pos);return ret;
}int main()
{string s = "abcdefg";string r = (s >> 3);cout << r << endl;return 0;
}

下一篇:关于师德的经典名言