Answers for "compare characters of string in c++"

C++
1

c++ compare char

// syntax
#include <cstring> // this needs to be at the top of the script/code
std::strcmp(<1st-char>,<2nd-char>)
  
// example (assuming: char_1 = 'Compare me'; char_2 = 'Compare_me')
#include <cstring>
if (std::strcmp(char_1,char_2) == 0) {
 std::cout << "The char's that you compared match!" << std::endl; 
}
else {
 std::cout << "The char's that you compared DON'T match" << std::endl; 
}

// OUTPUT: The char's that you compared match!

/*
NOTE: the following outputs of std::strcmp indicate:
[less than zero] : left-hand-side appears before right-hand-side in lexicographical order
[zero] : the chars are equal
[greater than zero] : left-hand-side appears after right-hand-side in lexicographical order
*/
Posted by: Guest on April-29-2020
1

how to compare two char* in c++

#include <string.h>
...
if (strcmp(firstSTR, secondSTR) == 0) {
    // strings are equal
    ...
} else {
    // strings are NOT equal
}
Posted by: Guest on January-14-2021
5

how to compare strings in c++

// comparing apples with apples
#include <iostream>
#include <string>

int main ()
{
  std::string str1 ("green apple");
  std::string str2 ("red apple");

  if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << 'n';

  if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an applen";

  if (str2.compare(str2.size()-5,5,"apple") == 0)
    std::cout << "and " << str2 << " is also an applen";

  if (str1.compare(6,5,str2,4,5) == 0)
    std::cout << "therefore, both are applesn";

  return 0;
}
Posted by: Guest on July-14-2020

Browse Popular Code Answers by Language