Hi,

I have made a small program to check if character arrays are the same(similar to string compare).This is my code so far:

// string Compare ()

#include <iostream>
using namespace std;

main(){

    char a[10] = {'a','b','c','d','e','f','g','h','i','j'};

    char b[10] = {'a','b','c','d','e','f','g','h','i','j'};

    for(int i = 0; i < 10; i++)
    {
        if(a[i] == b[i])
        {
            cout << "Strings are the same." << endl;
        }

        else
        {
            cout << "Strings not the same." << endl;
        }
    }

}

My problem is,that although it loops through the arrays and checks if each subscript is the same,it will print out that message numerous times,and i only want it to verify after they have all been checked.

If i put in a break,it will only check until the first subscript of each array meets the condition and then it breaks.So i know my problem lies somewere with the if statement,is it possible to have it check all subscripts and then verify?

You can do it this way

#include <iostream>
using namespace std;

int main(){

	int count = 0;

    char a[10] = {'a','b','c','d','e','f','g','h','i','j'};

    char b[10] = {'a','b','c','d','e','f','g','h','i','j'};

    for(int i = 0; i < 10; i++)
    {
        if(a[i] == b[i])
			count++;
		else
			count = 0;
    }
	
	if (count == 10)
		cout << "Strings are the same." << endl;

	else 
		cout << "Strings not the same." << endl;


	return 0;
}

Another way would be to write this as a function. If any character does not match, you can break the loop early and return a value indicating the "strings" do not match. If all characters do compare the same, then return a value indicating the "strings" do match.

#include <iostream>
using namespace std;

bool foo(const char *a, const char *b, int size)
{
   for ( int i = 0; i < 10; i++ )
   {
      if ( a[i] != b[i] )
      {
         return false; // not the same
      }
   }
   return true; // all characters were the same
}

int main()
{
   char a[10] = {'a','b','c','d','e','f','g','h','i','j'};
   char b[10] = {'a','b','c','d','e','f','g','h','i','j'};
   if ( foo(a,b,10) )
   {
      cout << "Strings are the same." << endl;
   }
   else
   {
      cout << "Strings not the same." << endl;
   }
}

Edited 7 Years Ago by Dave Sinkula: n/a

This question has already been answered. Start a new discussion instead.