比较两个字符串与字符 [英] Compare Two Strings with charater

查看:89
本文介绍了比较两个字符串与字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有2个文本框,用户可在其中输入相同长度的文本.我需要按字符进行比较.为此,我使用了Chars(i).现在,我一直在尝试突出显示字符串索引的不同之处.我无法为此找到解决方法.

例如:

string1 = HELLO
string2 = WELLM

当用户单击比较"按钮时,代码应突出显示H和W,以及O和M可能分别位于相同的文本框中或2个不同的标签等中.我几乎是VB编码的新手!很久以来一直在尝试执行此操作.

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.

推荐答案

尝试将其修改为所需的内容...

首先,添加对名称空间 Microsoft.VisualBasic
的引用 这样,允许Strings.Mid可用.

Try modifying this to what you want...

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

using Microsoft.VisualBasic;


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.");
            }


尝试一下:
C#:
Try this:
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.NET:

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.


这篇关于比较两个字符串与字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆