在C语言中,我们知道字符串基本上是一个以\ 0结尾的字符数组。因此,要对字符串进行操作,我们定义了字符数组。但是在C ++中,标准库为我们提供了将字符串用作基本数据类型(如整数)的便利。
示例
Like we define and declare, int i=5; Same way, we can do for a string like, String s= "NHOOO";
请记住,需要在“”下定义一个字符串变量(文字)。“ a”是字符,而“ a”是字符串。
访问字符串字符
返回字符串大小
相比
级联
需要的头文件:
#include <string> Or #include <bits/stdc++.h>
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; //打印尺寸/长度 cout<<"length of the "<<s<<" is = "<<s.length()<<endl; //添加两个字符串 string s1="Include"; string s2="Help"; cout<<"s1+s2: "<<s1+s2<<endl; //比较 if(s1==s2) cout<<s1<<" and "<<s2<<" are equal"<<endl; else cout<<s1<<" and "<<s2<<" are not equal"<<endl; //访问字符 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; }
输出结果
Enter your string NHOOO Sting you entered is: NHOOO length of the NHOOO is = 11 s1+s2: NHOOO Include and Help are not equal character at 0 index in NHOOO is = I character at 1 index in NHOOO is = n character at 5 index in NHOOO is = d