📜  C ++程序使用指针比较两个字符串

📅  最后修改于: 2021-05-31 20:51:09             🧑  作者: Mango

给定两个字符串,使用指针比较字符串

例子:

Input: str1 = geeks, str2 = geeks
Output: Both are equal

Input: str1 = hello, str2 = hellu
Output: Both are not equal
As their length are same but characters are different

想法是取消引用给定的指针,比较值并推进它们两者。

程序:

// C++ Program to compare two strings using
// Pointers
#include 
using namespace std;
  
  
// Method to compare two string
// using pointer
bool compare(char *str1, char *str2)
{
    while (*str1 == *str2)
    {
        if (*str1 == '\0' && *str2 == '\0')
            return true;
        str1++;
        str2++;
    }      
  
    return false;
}
  
int main()
{
    // Declare and Initialize two strings
    char str1[] = "geeks";
    char str2[] = "geeks";
  
    if (compare(str1, str2) == 1)
        cout << str1 << " " << str2 << " are Equal";
    else
        cout << str1 << " " << str2 << " are not Equal";
}
输出:
geeks geeks are Equal
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”