Compare c++ string characters and string arrangements ㅠㅠ

Asked 2 years ago, Updated 2 years ago, 81 views

I'm comparing string characters and string arrays.

#include <iostream>
#include <string>
int main(){
string Subway[] = {"Bulgwang", "Hapjeong", "Mapo-gu Office", "Mangwon"};
string a = "Telescence";
int count = 0;

for(int i=0; i<4; i++){
    if(a.compare(subway[i])==1)
         count++;
    }
}


I tried it like this, but the count value doesn't come out as 3 ㅠ<

How do I fix it,

c++ string array string-comparison

2022-09-22 17:58

1 Answers

The return value of std::string:compare() is greater than 0 or less than 0.

a.compare(b)

Therefore, a.compare(subway[i])==1 may not work as intended.

Given that the desired result is 3, it seems to be conditional on the same string or a string behind the dictionary.

Therefore, if you change to a.compare(subway[i]) <=0 as shown below, count increases only if the prior order is the same as the network or if it is followed.

#include <iostream>
#include <string>

using std::string;

int main(){
    string Subway[] = {"Bulgwang", "Hapjeong", "Mapo-gu Office", "Mangwon"};
    string a = "Telescence";
    int count = 0;

    for(int i=0; i<4; i++){
        if(a.compare(subway[i]) <= 0)
             count++;
    }
    std::cout << count;
    return 0;
}


2022-09-22 17:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.