大小写不敏感

7
If TextBox2.Text = "a" AndAlso TextBox21.Text = "a" Then
        'MessageBox.Show("A")
        totCorrect = totCorrect + corAns
    ElseIf TextBox2.Text = "b" AndAlso TextBox21.Text = "b" Then
        'MessageBox.Show("B")
        totCorrect = totCorrect + corAns
    ElseIf TextBox2.Text = "c" AndAlso TextBox21.Text = "c" Then
        'MessageBox.Show("C")
        totCorrect = totCorrect + corAns
    ElseIf TextBox2.Text = "d" AndAlso TextBox21.Text = "d" Then
        'MessageBox.Show("D")
        totCorrect = totCorrect + corAns
    Else
        totWrong = totWrong + wrgAns
        Label13.Visible = True
    End If

我正在尝试使用户输入的字母a、b、c、d不区分大小写。尝试使用UCase,但它没有起作用(不确定是否使用不正确)。我在Visual Studio 2012中使用VB。任何参考资料都将非常有帮助。


2
请查看此链接:http://msdn.microsoft.com/zh-cn/library/system.string.compare(v=vs.80).aspx - David
2个回答

21

您可以使用String.Compare方法:String.Compare(String strA, String strB, Boolean ignoreCase)

ignoreCase参数传递为true将执行大小写不敏感的比较。

If String.Compare(TextBox2.Text, "a", true) = 0 AndAlso String.Compare(TextBox21.Text, "a", true) = 0 Then
        'MessageBox.Show("A")
        totCorrect = totCorrect + corAns
    ElseIf String.Compare(TextBox2.Text, "b", true) = 0 AndAlso String.Compare(TextBox21.Text, "b", true) = 0 Then
        'MessageBox.Show("B")
        totCorrect = totCorrect + corAns
    ElseIf String.Compare(TextBox2.Text, "c", true) = 0 AndAlso String.Compare(TextBox21.Text, "c", true) = 0 Then
        'MessageBox.Show("C")
        totCorrect = totCorrect + corAns
    ElseIf String.Compare(TextBox2.Text, "d", true) = 0 AndAlso String.Compare(TextBox21.Text, "d", true) = 0 Then
        'MessageBox.Show("D")
        totCorrect = totCorrect + corAns
    Else
        totWrong = totWrong + wrgAns
        Label13.Visible = True
    End If

另一个想法是使用ToUpperToLower函数将输入转换为大写或小写。

If TextBox2.Text.ToUpper() = "A" AndAlso TextBox21.Text.ToUpper() = "A" Then
            'MessageBox.Show("A")
            totCorrect = totCorrect + corAns
        ElseIf TextBox2.Text.ToUpper() = "B" AndAlso TextBox21.Text.ToUpper() = "B" Then
            'MessageBox.Show("B")
            totCorrect = totCorrect + corAns
        ElseIf TextBox2.Text.ToUpper() = "C" AndAlso TextBox21.Text.ToUpper() = "C" Then
            'MessageBox.Show("C")
            totCorrect = totCorrect + corAns
        ElseIf TextBox2.Text.ToUpper() = "D" AndAlso TextBox21.Text.ToUpper() = "D" Then
            'MessageBox.Show("D")
            totCorrect = totCorrect + corAns
        Else
            totWrong = totWrong + wrgAns
            Label13.Visible = True
        End If

3
根据MSDN文档,在VB.NET中,您可以通过在文件中添加一行代码来使用“Option Compare语句”。请参考以下代码:Option Compare语句
Option Compare Text

如果您在代码开头添加上述行,您就是在告诉CLR从默认的(Option Compare Binary)切换到不区分大小写比较作为 = 操作符的新默认设置。
我不知道是否有任何C#的替代方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接