C++---STL标准库之string函数超长解析,十大常用函数全覆盖,轻松掌握,灵活运用,全面解决string字符串难题!

STL---string

    • string()定义
    • string 中内容的访问
    • string常用函数

string()定义

在 C 语言中,一般使用字符数组 char str[]来存放字符串,但是使用字符数组有时会显得操作麻烦,而且容易因经验不足而产生一些错误。为了使编程者可以更方便地对字符串进行操作,C++在 STL 中加入了string 类型,对字符串常用的需求功能进行了封装,使得操作起来更方便,且不易出错。

如果要使用 string,需要添加string头文件,即#include < string >(注意 string.h 和 string是不一样的头文件)。除此之外,还需要在头文件下面加上一句∶"using namespace std;",这样就可以在代码中使用string了。下面来看string的一些常用用法。

string的定义
定义string的方式跟基本数据类型相同,只需要在string后跟上变量名即可∶

 string str;

如果要初始化,可以直接给 string类型的变量进行赋值∶

 string str = "abcd"; 

string 中内容的访问

(1)通过下标访问
一般来说,可以直接像字符数组那样去访问string∶

#include
#include

using namespace std;

//string

int main()
{
   
	string str = "abcd";
	
	for(int i = 0; i < str.length(); i++)
	{
   
		cout << str[i] << endl;
	}
	
	return 0;
}

输出结果:

a
b
c
d

如果要读入和输出整个字符串,则只能用cin和cout:

#include
#include

using namespace std;

int main()
{
   
	string str;
	
	cin >> str;
	cout << str;
	
	return 0;
}

输出结果:任意输入都会输出同样的字符串。

也可使用c_str()将string类型转为字符数组进行输出:

#include
#include
#include

using namespace std;

//str.c_str

int main()
{
   
	string str = "abcd";
	
	printf("%s\n",str.c_str());
	
	return 0;
}

输出结果:

abcd

(2)通过迭代器访问

一般仅通过(1)即可满足访问的要求,但有些函数比如insert()与erase()则要求以迭代器为参数:

由于string不像其他STL容器那样需要参数,因此可以直接如下定义:

string::iterator it;

这样就得到了迭代器it,并且可以通过访问*it来访问string里的每一位

#include
#include

using namespace std;

int main()
{
   
	string str = "abcd";
	
	for(string::iterator it = str.begin(); it != str.end(); it++)
	{
   
		cout << *it << endl;
	}
	
	return 0;
} 

你可能感兴趣的:(笔记,c++,c语言,c#,算法,数据结构)