string
C语言中,一般使用字符数组来表示字符串
char str[100] = "I love China";
C++中,也可以用到string类型来表示字符串,string和字符数组之间还可以相互转换,string类型里提供了更多操作字符串的方法,string用起来会更加方便 string也位于std命名空间中, 方便使用可以加: using namespace std; 头文件: #include < string > 常用方法:
#include <string>
string s1;
string s2 = "I love China";
string s3("I love China");
string s4 = s2;
int num = 6;
string s5(num, 'a');
string对象上的操作
1.判断是否为空
返回布尔类型
string s1;
if (s1.empty())
{
cout << "s1为空" << endl;
}
2.size()/length();
返回类型/字符数量
string s1;
cout << s1.size() << endl;
cout << s1.length() << endl;
string s2 = "I love China";
cout << s2.size() << endl;
cout << s2.length() << endl;
string s3 = "你好";
cout << s3.size() << endl;
cout << s3.length() << endl;
3.s[n]
返回s中的第n个字符, n代表位置, 从0开始, 到size()-1
string s3 = "I love China";
if (s3.size() > 4)
{
cout << s3[4] << endl;
s3[4] = 'w';
}
cout << s3 << endl;
4.s1+s2
字符串连接
string s1 = "abcd";
string s2 = "hijk";
cout << s1 + s2 << endl;
5.s1 = s2
赋值
string s1 = "abcd";
string s2 = "ab";
s1 = s2;
cout << s1 << endl;
6.s1 == s2
判断是否相等 注意:大小写敏感
string s1 = "ab";
string s2 = "ab";
if (s1 == s2)
{
cout << "相等" << endl;
}
7. s1 != s2
同上反例
8. s.c_str()
返回一个字符串s中的内容指针,返回是一个指向正规C字符串的常量指针, 所以是以’\0’结尾的.
string s1 = "abc";
const char* p = s1.c_str();
char str[100];
strcpy_s(str, sizeof(str), p);
cout << str << endl;
9.相加""+’’
例:
string s1 = "abc";
string s2 = "abC";
cout << s1 + " and " + s2 + 'D' << endl;
10.范围for
c11中范围for: 能够遍历序列中的每一个元素
string s1 = "I love China";
for (auto c : s1)
{
cout << c;
}
例2:
string s1 = "I love China";
for (auto &c : s1)
{
c = toupper(c);
}
cout << s1;
|