Impostor
Impostor

Reputation: 2050

Comparing data in different structure

I have a string

string cubeinline = "12345123451234X1234512345";

which is equal to a List<string>

List<string> cube = new List<string>(){ "12345",
                                        "12345",
                                        "1234X",
                                        "12345",
                                        "12345"};

But different arranged. The string is split by length. In this case 5.

Now i need to compare the string with the List - char by char. But my method says every char is invalid.

int maxLength = 5;
for (int i = 0; i < cubeinline.Length; i++)
{
    if (cubeinline[i] == cube[i / maxLength][i % maxLength])
    {
        Console.WriteLine("Error in char" + i);
    }
}

Upvotes: 3

Views: 121

Answers (5)

Salah Akbari
Salah Akbari

Reputation: 39976

I use LINQ for this purpose usually. In this approach you are using the SequenceEqual method which checks two sequences (one is cube and one is Splitted string into 5 size) and checks whether two sequences are equal by comparing the elements or not:

bool res = cube.SequenceEqual(Enumerable.Range(0, cubeinline.Length / 5)
    .Select(i => cubeinline.Substring(i * 5, 5)));

Upvotes: 1

Pseudo Sudo
Pseudo Sudo

Reputation: 1412

What is the reasoning for storing the strings in a list? Even if you must keep them in the list, you can use a string temp variable to combine the strings in the list into a single string, then use the String.Equals method to compare your string and the temp string.

This method is better for comparing strings based on values as == checks reference equality. Heres another question you should check out.

Upvotes: 0

A.B.
A.B.

Reputation: 1604

Change your if condition to

if ( cubeinline[i] != cube[i / maxLength][i % maxLength] )
{
    Console.WriteLine ("Error in char" + i);
}

OR please add else condition,

if ( cubeinline[i] == cube[i / maxLength][i % maxLength] )
{
    Console.WriteLine ("Match found at " + i);
}
else
{
    Console.WriteLine ("Error in char" + i);
}

Upvotes: 0

MichaelThePotato
MichaelThePotato

Reputation: 1525

you can do it like this:

string cubeinline = "12345123451234X1234512345";
List<string> cube = new List<string>(){ "12345",
                                    "12345",
                                    "1234X",
                                    "12345",
                                    "12345"};
bool isEqual = cubeinline == string.Concat(cube);

Upvotes: 1

AhmadWabbi
AhmadWabbi

Reputation: 2197

Change == into !=. You inverse the logic here: the program should display the message when there is a difference, not an equlity!

Upvotes: 10

Related Questions