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++, the standard library gives us the facility to use the string as a basic data type like an integer. Like integer comparisons, we can do the same for strings too.
在C语言中,我们知道字符串基本上是一个以\ 0结尾的字符数组。 因此,要对字符串进行操作,我们定义了字符数组。 但是在C ++中,标准库为我们提供了将字符串用作基本数据类型(如整数)的便利。 像整数比较一样,我们也可以对字符串进行相同的操作。
Example:
例:
Like we define and declare,
int i=5, j=7;
Same way, we can do for a string like,
string s1="Include", s2="Help";
Like integers (i==j) , (i>j), (i<j)
We can also do the same like
if(s1==s2)
cout << 'They are same\n";
else if(s1>s2)
cout<<s1<<" is greater\n";
else
cout<<s2<< "s2 is greater\n";
Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.
请记住,需要在“”下定义一个字符串变量(文字)。 “ a”是字符,而“ a”是字符串。
两个字符串之间的比较如何工作? (How comparison between two string works?)
'==' operator
'=='运算符
Two strings need to be lexicographically same to return true which checking for == operator. "Include" and "Include" is the same. But, "INCLUDE" and "Include" is not same, i.e., case matters.
两个字符串在字典上必须相同才能返回true,这将检查==运算符。 “包含”和“包含”相同。 但是, “ INCLUDE”和“ Include”不相同,即大小写有关。
'>' , '
'>','
This two operator checks which string is greater(smaller) lexicographically. The checking starts from the initial character & checking is done as per ascii value. The checking continues until it faces the same character from both strings. Like,
这两个运算符在字典上检查哪个字符串更大(或更小)。 从初始字符开始检查,并根据ascii值进行检查。 继续检查,直到面对两个字符串中的相同字符。 喜欢,
"Include" > "Help" as 'I' > 'H'"Include" < "India" as 'c' < 'd'
Header file needed:
所需的头文件:
#include <string>
Or
#include <bits/stdc++.h>
C++ program to compare two strings using comparison operator (==)
C ++程序使用比较运算符(==)比较两个字符串
#include <bits/stdc++.h>
using namespace std;
void compare(string a, string b){
if(a==b)
cout<<"strings are equal\n";
else if(a<b)
cout<<b<<" is lexicografically greater\n";
else
cout<<a<<" is lexicografically greater\n";
}
int main(){
string s1,s2;
cout<<"enter string1\n";
cin>>s1;
cout<<"enter string2\n";
cin>>s2;
compare(s1,s2); //user-defined function to comapre
return 0;
}
Output
输出量
First run:
enter string1
Include
enter string2
Help
Include is lexicografically greater
Second run:
enter string1
Include
enter string2
India
India is lexicografically greater
翻译自: https://www.includehelp.com/stl/comparing-two-string-using-comparison-operators-in-cpp-stl.aspx
stl取出字符串中的字符