当前位置: 移动技术网 > IT编程>开发语言>C/C++ > string类型介绍

string类型介绍

2019年02月25日  | 移动技术网IT编程  | 我要评论

焚神焚峰,日本vs希腊,秘方大全

一、前言

int,float,char,c++标准库提供的类型:string,vector。

string:可变长字符串的处理;vector一种集合或者容器的概念。

二、string类型简介

c++标准库中的类型,代表一个可变长的字符串

char str[100] = “i love china”; // c语言用法

三、定义和初始化string对象

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s1; // 默认初始化,s1=””,””空串,表示里面没有字符
    string s2 = “i love china”; // 把i love china 这个字符串内容拷贝到了s2代表的一段内存中,拷贝时不包括末尾的\0;
    string s3(“i love china”); // 与s2的效果一样。
    string s4 = s2; // 将s2中的内容拷贝到s4所代表的的一段内存中。

    int num = 6;
    string s5 = (num,’a’);// 将s5初始化为连续num个字符的’a’,组成的字符串,这种方式不太推荐,因为会在系统内部创建临时对象。
    return 0;
}

 

四、string对象上的操作

(1)判断是否为空empty(),返回的布尔值

string s1;
if(s1.empty()) // 成立
{
    cout << “s1字符串为空” <<endl;
}

(2)size()/length():返回字节/字符数量,代表该字符串的长度。unsigned int

string s1;
cout << s1.size() << endl; // 0
cout << s1.length() << endl; // 0
string s2 = “我爱中国”;
cout << s2.size() << endl;// 8
cout << s2.length() << endl; // 8
string s3 = “i love china”;
cout << s3.size() << endl;// 12
cout << s3.length() << endl; // 12

(3)s[n]:返回s中的第n个字符,(n是个整型值),n代表的是一个位置,位置从0开始,到size()-1;

如果用下标n超过这个范围的内容,或者本来是一个空字符串,你用s[n]去访问,都会产生不可预测的作用。

string s3 = “i love china”;
if(s3.size()>4)
{
    cout << s3[4] << endl;
    s3[4] = ‘2’;
}
cout << s3 << endl; // i lowe china

(4)s1+s2:字符串的连接,返回连接之后结果,其实就是得到一个新的string对象。

string s4 = “abcd”;
string s5 = “efgk”
string s6 = s4 + s5;
cout << s6 <<endl;

(5)s1 = s2:字符串对象赋值,用s2中的内容取代s1中的内容

string s4 = “abcd”;
string s5 = “efgk”
s5 = s4;
cout << s5 <<endl; // abcd

(6)s1 == s2:判断两个字符串是否相等。大小写敏感:也就是大小写字符跟小写字符是两个不同的字符。相等:长度相同,字符全相同。

string s4 = “abcd”;
string s5 = “abcd”
if(s5 == s4)
{
  cout << “s4 == s5” <<endl; // abcd
}

(7)s1 != s2:判断两个字符串是否不相等

string s4 = “abcd”;
string s5 = “abcd”
if(s5 != s4)
{
    cout << “s4 != s5” <<endl; // abcd
}

(8)s.c_str():返回一个字符串s中的内容指针,返回一个指向正规c字符串的指针常亮,也就是以\0存储。

这个函数的引入是为了与c语言兼容,在c语言中没有string类型,所以我们需要通过string对象的c_str()成员函数将string对象转换为c语言的字符串样式。

string s4 = “abcd”;
const char *p = s4.c_str(); // abcd
char str[100];
strcpy_s(str,sizeof(str),p);
cout << str << endl;

string s11(str); // 用c语言的字符串数组初始化string类型。

(9)读写string对象

string s1;
cin >> s1; // 从键盘输入
cout << s1 << endl;

(10)字面值和string相加

string str1 = “abc”;
string str2 = “def”;
string str3 = s1 + “ and ” + s2 + ‘e’; // 隐式类型转换
cout << str3 << endl;  // abc and defe;
// string s1 = “abc” + “def”; // 语法上不允许

(11)范围for针对string的使用:c++11提供了范围for:能够遍历一个序列的每一个元素。string可以看成一个字符序列。

string s1 = “i love china”;
for(auto c:s1) // auto:变量类型自动推断
{
    cout << c << endl; // 每次输出一个字符,换行
}

for(auto &c:s1) // auto:变量类型自动推断
{
    // toupper()把小写字符转换为大写,大写字符不变
    c = toupper(c); // 因为c是一个引用,所以这相当于改变s1中的值
}
cout << s1 << endl;

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网