Comparing char array in c++
Hello friends,
In the following code I am comparing char arrays:
Code:
int compare(unsigned char * x, unsigned char * y)
{
int k;
for(k=0;k<MAX_ARRAY_SIZE;k++)
if(x[k]!=x[k])
return 1;
return 0;
}
Can anyone tell me is there any better way of comparing char array in c++. Please help me.
Thanks in advanced.
Re: Comparing char array in c++
What type of unsigned characters there are in array? If you are using array of binary data then you cannot use strcmp() function. As per my knowledge strcmp() is used for comparing strings. This function compare each character of string with another until last character. If your string is big then you can not use this function.
Re: Comparing char array in c++
There is no need to use any function to to compare two char array in c++, you can easily do this using while loop. I have written following code for you. Just try to understand it. It is very simple program.
Code:
int compare(unsigned char *x, unsigned char *y, int sizes) {
while(size-- > 0) {
if ( *x != *y ) { return (*x < *y ) ? -1 : 1; }
x++; y++;
}
return 0;
}
Re: Comparing char array in c++
You can use following code for Comparing char array in c++. It is very simple one. In the following program I have take input from the user and then I have store this input in one variable and after that I have compare these two variables.
Code:
#include <iostream>
using namespace std;
int main ()
{
char questions[] = "enter your address ";
char greeting[] = "welcome, ";
char youradress[200];
cout << questiona;
cin >> youraddress;
cout << greeting << youraddress << "!";
return 0;
}
Re: Comparing char array in c++
Hey it is very simple program to compare character array in c++. Just look at following code. I have written following code for you. In the following code I have create two array variable and take input in this array variable. After this I compare these two array variable using If-else statement.
Code:
#include <iostream.h>
int main()
{
char ns1 [20] = "Hello to all";
char ns2 [20] = "Hello to all";
if (ns1==ns2)
{
cout <<1;
}
else
{
cout << 0;
}
return 0;
}
Re: Comparing char array in c++
You can easily compare char array in c++ using following program. I have written this code for you. In the following code I have use iostream.h class to include all input and output methods. In the following code I have use std::string function to compare char array.
Code:
#include <iostream.h>
#include <string>
int main()
{
char nsw1 [10] = "Welcome to this world";
char nsw2 [10] = "Welcome to this world";
if (strcmp(nsw1,nsw2) == 0) {
cout << "match\n";
}
else {
cout << "doesn't match\n";
}
std::string ans1 = "Welcome to this world";
std::string ans2 = "Welcome to this world";
if (ans1 == ans2) {
cout << "matches\n";
}
else {
cout << "doesn't match\n";
}
return 0;
}