Darkmenon
Darkmenon

Reputation: 13

How to compare 2 character strings?

I am making a typing game and I need to compare a generated string and input string character by character to and then calculate % accuracy.

But it seems am missing something because the function does no compare well.

Am I doing something wrong ?

private void Button_Click(object sender, RoutedEventArgs e)
    {
        int percentage = 0;
        int mistakes = 0;
        string input = TextBox1.Text;

        string letter = TextBox2.Text;
        char[] letters1 = letter.ToCharArray();
        char[] input1 = input.ToCharArray();

        for (int j = 0; j < input1.Length; j++)
        {
            if (input1[j] != letters1[j])
                mistakes = mistakes +1;   

            else if (input1[j] == letters1[j])
                mistakes = mistakes;
        }

        percentage = 100 - ((mistakes / letters1.Length) * 100);
        Label2.Content = percentage;


    }

Upvotes: 0

Views: 83

Answers (2)

Jim Experts
Jim Experts

Reputation: 3

Hope this works for you.

private void Button_Click(object sender, RoutedEventArgs e)
    {
        float percentage = 0;
        float mistakes = 0;
        string input = TextBox1.Text;

        string letter = TextBox2.Text;
        char[] letters1 = letter.ToCharArray();
        char[] input1 = input.ToCharArray();

        for (int j = 0; j < input1.Length; j++)
        {
            if (input1[j] != letters1[j])
            {
                mistakes++; 
            }

        }

        percentage = 100 - ((mistakes / letters1.Length) * 100);
        Label2.Content = percentage.ToString();
    }

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66449

You're performing integer arithmetic and losing the fractional portion of the result of your division. When you divide two integers, the result is another integer (and you lose the fractional part).

percentage = 100 - ((mistakes / letters1.Length) * 100);

Given your code above, and assuming letters1 is 30 characters long and there are 20 mistakes, then 20 / 30 (or any amount of mistakes from the total characters available, except when every character is wrong), will result in:

percentage = 100 - ((20 / 30) * 100);

          // 100 - ((0) * 100) == 100

Converting one of those values to a double should retain the fractional portion of the division:

percentage = 100 - ((mistakes / Convert.ToDouble(letters1.Length) * 100);

        // = 100 - ((20 / 30.0) * 100) == 100 - ((0.6666666) * 100) == 33.333333

Upvotes: 1

Related Questions