龙空技术网

string对象的基本使用

c语言爱好学习 53

前言:

如今兄弟们对“c语言定义一个string类型的数组”大致比较关注,朋友们都需要剖析一些“c语言定义一个string类型的数组”的相关知识。那么小编在网络上搜集了一些有关“c语言定义一个string类型的数组””的相关资讯,希望朋友们能喜欢,看官们快快来了解一下吧!

string对象的基本使用

C++标准模板库中提供了string数据类型,专门用于处理字符串。string是一个类,这个类型的变量称为“string对象”

1、要在程序中使用string对象,必须在程序中包含头文件string,即在程序的最前面,要加上如下语句:#include<string>

2、声明一个string对象,与声明普通变量是类似的,格式如下:string 变量名;

string str1; //声明string对象str1,值为空

string city="Beijing"; //声明string对象city,并使用字符串常量进行初始化

string str2=city; //声明string对象str2,并使用字符串变量进行初始化

cout<<"str1="<<str1<<"."<<endl;

cout<<city<<","<<str2<<endl;

//还可以使用字符数组对string变量进行初始化。例如:

char name[ ]="C++程序";

string s1=name;

//还可以声明一个string对象数组,即数组中每个元素都是字符串。例如:

string citys[ ]={"Beijing","Shanghai","Tianjin","Chongqing"};

cout<<citys[1]<<endl; //输出Shanghai,数组下标从0开始

cout<<sizeof(citys)/sizeof(string)<<endl; //输出数组元素个数

sizeof(string);//是每个string对象的大小,所以sizeof(citys)/sizeof(string)表示的是数组元素个数。

1、字符串的连接: +号

string s2="C++";

string s3="C";

cout<<"s2= "<<s2<<endl;//s2= C++

cout<<"s3= "<<s3<<endl;//s3= C

cout<<s3+s2<<endl; //CC++

2、字符串判断空:empty()

string str; //未初始化,空串

if(str.empty()){

cout<<"str is NULL."<<",length="<<str.length()<<endl;//str is NULL.,length=0

} else{

cout<<"str is not NULL."<<endl;

}

```

3、字符串的追加:append()

```cpp

string str; //未初始化,空串

str=str.append("ABC").append("DEFG");

cout<<"str is "<<str<<",size="<<str.size()<<endl;//str is ABCDEFG,size=7

4、字符的查找:find()

string str; //未初始化,空串

str=str.append("ABC").append("DEFG");

cout<<"str is "<<str<<",size="<<str.size()<<endl;//str is ABCDEFG,size=7

const char *p=str.c_str();

cout<<"*p="<<*p<<endl;//*p=A

cout<<"p="<<p<<endl;//p=ABCDEFG

//1、find 函数 返回jk 在s 中的下标位置

cout<<"find:"<<str.find("D")<<endl; //查找成功,find:3

cout<<"find:"<<str.find("F")<<endl; //查找成功,find:5

//2、返回子串出现在母串中的首次出现的位置,和最后一次出现的位置。

cout<<"find_first_of:"<< str.find_first_of("A")<<endl;//find_first_of:0

cout<<"find_last_of:"<< str.find_last_of("A")<<endl;//find_last_of:0

//3、查找某一给定位置后的子串的位置

//从字符串str 下标4开始,查找字符串D ,返回D 在str 中的下标

cout<<"find:"<<str.find("D",4)<<endl; //查找失败:find:4294967295

//从字符串str 下标0开始,查找字符串F ,返回F 在str 中的下标

cout<<"find:"<<str.find("F",0)<<endl; //查找成功,find:5

5、字符的插入:insert()

string str; //未初始化,空串

str=str.append("ABC").append("DEFG");

//4、字符串的插入

string str1=str.insert(4,"123");//从下标4的位置插入

cout<<str1<<endl;//ABCD123EFG

原文链接:

大家有兴趣学习C/C++的可以加下方QQ群,大家一起学习呀!!!

QQ群:1083020561

标签: #c语言定义一个string类型的数组