[英]C++ trying to see if an input string is equal to a array string of a class
[英]Equal strings (string and string of array)-c++
我不明白如何在C ++中的字符串之間進行比較?
string s1="abc";
string s[]={"abc","vsj"};
int length=sizeof(s)/sizeof(s[0]);//length of s
for(int i=0;i<length;i++)
{
if(s[i].compare(s1))
{
cout<<"One of the string equal to s1";
}
}
可能嗎?? 謝謝..
std::string
重載operator==
。 您可以使用operato==
比較2個字符串。 您也可以使用std::vector
而不是array。 使用c ++ 11:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s1="abc";
vector<string> ss = { "abc", "vsj" };
for (auto &s: ss) {
if (s == s1) {
cout<<"One of the string equal to s1";
}
}
return 0;
}
使用c ++ 98:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s1="abc";
vector<string> ss;
ss.push_back("abc");
ss.push_back("vsj");
for (size_t i = 0; i < ss.size(); ++i) {
if (ss.at(i) == s1) {
cout<<"One of the string equal to s1";
}
}
return 0;
}
比較返回與strcmp相同的值:
<0-不匹配的第一個字符在ptr1中的值比在ptr2中的值低
0-兩個字符串的內容相等
> 0-不匹配的第一個字符在ptr1中的值大於在ptr2中的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.