stl标准模板库
字符串作为数据类型 (String as datatype)
In C, we know string basically a character array terminated by \0. Thus to operate with the string we define character array. But in C++, standard library gives us the facility to use string as a basic data type like integer.
在C语言中,我们知道字符串基本上是一个以\ 0结尾的字符数组。 因此,要对字符串进行操作,我们定义了字符数组。 但是在C ++中,标准库为我们提供了将字符串用作基本数据类型(如整数)的便利。
Example:
例:
Like we define and declare,
int i=5;
Same way, we can do for a string like,
String s= "IncludeHelp";
Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.
请记住,需要在“”下定义一个字符串变量(文字)。 “ a”是字符,而“ a”是字符串。
可以对字符串执行的基本操作 (Basic operation that can be performed on string)
Header file needed:
所需的头文件:
#include <string>
Or
#include <bits/stdc++.h>
C++ program to demonstrate example of std::string
C ++程序演示std :: string的示例
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
//reading & printing
cout<<"Enter your string\n";
cin>>s;
cout<<"Sting you entered is: "<<s<<endl;
//printing size/length
cout<<"length of the "<<s<<" is = "<<s.length()<<endl;
//adding two strings
string s1="Include";
string s2="Help";
cout<<"s1+s2: "<<s1+s2<<endl;
//comparing
if(s1==s2)
cout<<s1<<" and "<<s2<<" are equal"<<endl;
else
cout<<s1<<" and "<<s2<<" are not equal"<<endl;
//accessing characters
cout<<"character at 0 index in "<<s<<" is = "<<s[0]<<endl;
cout<<"character at 1 index in "<<s<<" is = "<<s[1]<<endl;
cout<<"character at 5 index in "<<s<<" is = "<<s[5]<<endl;
return 0;
}
Output
输出量
Enter your string
IncludeHelp
Sting you entered is: IncludeHelp
length of the IncludeHelp is = 11
s1+s2: IncludeHelp
Include and Help are not equal
character at 0 index in IncludeHelp is = I
character at 1 index in IncludeHelp is = n
character at 5 index in IncludeHelp is = d
翻译自: https://www.includehelp.com/stl/std-string-in-cpp-stl-standard-template-library.aspx
stl标准模板库