4. The string type in c++

A built-in data type string is provided in C++, which can replace the char array in C language. When you need to use the string data type, you need to include the header file string in the program.

1. Simple assignment of string type

#include <iostream>
#include <string>
using namespace std ;
int main ()
{
string s1; //default is empty
string s2 = "123456" ; //Direct string assignment, there is no '\0' at the end of the string type
string s3 = s2; //The value of s2 is directly assigned to s3
string s4 ( 10 , 's' ); //The variable s4 is initialized to a string of 10 's' characters, which is "ssssssssss".
cout<< "s1 = " <<s1<<endl;
cout<< "s2 = " <<s2<<endl;
cout<< "s3 = " <<s3<<endl;
cout<< "s4 = "<<s4<<endl;
return 0;
}

ubuntu下打印结果:


2.string长度

string s1 = "123456";
cout<<s1. length()<<endl;
//使用c_str转换为字符串
cout << "buf = "<<s1. c_str()<<endl;
cout << "sizeof = "<< sizeof(s1. c_str())<<endl;
cout << "strlen = "<< strlen(s1. c_str())<<endl;

ubuntu运行结果:


3.string的输入输出

string s1;
cout<< "in = ";
cin>>s1;
cout<< "out = "<<s1<<endl;

ubuntu输出结果为:


注意:string输入不可以有空格,否则会出现数据输出不完整现象.


4.string类型字符串的拼接

//使用 + 和 += 进行拼接
string s1 = "nihao";
string s2 = "wo";
string s3 = s1 + s2;
s3 += "shi";
s3 += "shui";
cout<< "s3 = "<<s3<<endl;

5.字符串修改

//字符串修改
string s1 = "helwo";
s1[ 3]= 'l';
cout<< "s1 = "<<s1<<endl;

ubuntu打印结果为:


6.删除字符串erase

erase函数可以删除string类型变量中的一个子字符串。erase函数有两个参数,第一个参数是要删除的子字符串的起始下标,第二参数是要删除子字符串的长度,如果第二个参数不指名的话则是直接从第一个参数获取起始下标,然后一直删除至字符串结束。

//erase函数
string s1 = "hello world";
s1. erase( 5); //获取前5个,删除到字符串介素
cout<< "s1 = "<<s1<<endl;

string s2 = "hello world";
s2. erase( 5, 3); //从起始下班5往后3个长度的全部删除
cout<< "s2 = "<<s2<<endl;

ubuntu的打印结果为:


7.insert函数

函数insert可以在string字符串中指定的位置插入另一个字符串,该函数同样有两个参数,第一个参数表示插入位置,第二参数表示要插入的字符串,第二个参数既可以是string变量,又可以是C风格的字符串

//insert函数
string s1 = "hllo";
s1. insert( 1, "e");
cout<< "s1 = "<<s1<<endl; //从下表1中增加e


8.replace函数

replace函数可以用一个指定的字符串来替换string类型变量中的一个子字符串,该函数有三个参数,第一个参数表示待替换的子字符串的其实下标,第二个参数表示待替换子字符串的长度,第三个参数表示要替换子字符串的字符串。第三个参数同样可以是string类型变量或C风格字符串。

//replace函数
string s1 = "hello home";
s1. replace( 6, 5, "world");
cout<< "s1 = "<<s1<<endl;

ubuntu上的打印结果为:


9.swap函数

swap函数可以用于将两个string 类型变量的值互换。

//swap函数
string s1 = "hello";
string s2 = "world";
s1. swap(s2);
cout<< "s1 = "<<s1<<endl;
cout<< "s2 = "<<s2<<endl;

ubuntu上的打印结果为:


10.substr

函数substr可以提取string字符串中的子字符串,该函数有两个参数,第一个参数为需要提取的子字符串的起始下标,第二个参数是需要提取的子字符串的长度。

//substr函数
string s1 = "hello my home";
string s2 = s1. substr( 6, 2);
cout<< "s2 = "<<s2<<endl;

ubuntu上的打印结果为:


11.find函数

find函数可以在字符串中查找子字符串中出现的位置。该函数有两个参数,第一个参数是待查找的子字符串,第二个参数是表示开始查找的位置,如果第二个参数不指名的话则默认从0开始查找,也即从字符串首开始查找。

string s1 = "hello world";
int index = s1. find( "world", 0);
cout<<index<<endl;

ubuntu上的打印结果是:

12.字符串的比较

“==”、 “!=”、 “<=”、 “>=”、 “<”和“>”操作符都可以用于进行string类型字符串的比较,这些操作符两边都可以是string字符串,也可以一边是string字符串另一边是字符串数组。

此处不在举例.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857651&siteId=291194637