Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Hi,

I have 2 textboxes where the user enters texts of same length. I need to do a char by char comparison. For this, i used Chars(i). Now, i have been trying to highlight the differences at the string index which is different. I am not able to figure a way out for that.

for example:

string1 = HELLO
string2 = WELLM

When the user hits Compare button, the code should highlight H and W, and also O and M maybe in the same respective textboxes or 2 different labels etc. Could you suggest ideas as to how i can do that? I am pretty much a newbie with VB coding! Have been trying to do this for a long time.
Posted
Updated 3-Oct-12 20:00pm
v2
Comments
Sergey Alexandrovich Kryukov 4-Oct-12 1:57am    
If you are a newbie, you need more effort, not less, but what you show here is nearly zero effort. Going to be experienced, ever?
--SA
Rockstar_ 4-Oct-12 2:10am    
You have to generate dynamic labels based on the highest length of the textbox values, then fill the text property of the labels with the chars from the textbox and also set the forecolor of the label based on the index of the unmatched char.
DaveAuld 4-Oct-12 4:31am    
One option is to use a loop and also character index positions, go figure.

Try modifying this to what you want...

First, add reference to the namespace Microsoft.VisualBasic
this, allows Strings.Mid to be available.

C#
using Microsoft.VisualBasic;

C#
string First = "Hello";
            string Test = "Wello";

            int unMatch = 0;
            int Place = 1;

            foreach (char current in First)
            {
                if (Place == Test.Length) break;
                if (current.ToString() != Strings.Mid(Test, Place, 1))
                {
                    unMatch++;
                }
                Place++;
            }

            MessageBox.Show(unMatch + " unmatched character(s) found.");
            }
 
Share this answer
 
v2
Try this:
C#:
C#
List<int> unequalPositions = new List<int>();
            string str1 = "HELLO";
            string str2 = "WELLM";
            for (int i = 0; i < str1.Length; i++)
            {
                if (str1[i] != str2[i])
                {
                    unequalPositions.Add(i);
                }
            }


VB.NET:
VB
Dim unequalPositions As New List(Of Integer)()
Dim str1 As String = "HELLO"
Dim str2 As String = "WELLM"
For i As Integer = 0 To str1.Length - 1
    If str1(i) <> str2(i) Then
        unequalPositions.Add(i)
    End If
Next


Now, you'll find the zero-based unequal positions in the List.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900