0

我的代码有一个小问题,我正在读取一个文本文件并显示来自用户输入的匹配项。唯一的问题是它区分大小写,例如,如果 Steve 中的 S 是小写的,它不会显示匹配项,因为它在文本 File 中是大写的。这是我正在使用的代码。

string name;

lstResult.Items.Clear();

using (StreamReader sr = File.OpenText("../Name_Check.txt"))
{                
    while ((name = sr.ReadLine()) != null)
    {                    
        if (txtInput.Text == name)
        {                       
            lstResult.Items.Add(name);
4

3 回答 3

4

尝试这个

 txtInput.Text.Equals(name, StringComparision.OrdinalIgnoreCase)

您可能必须根据您的文化更改最后一个选项。

于 2013-05-28T12:20:51.653 回答
2

您可以使用String.Equals(string, string, StringComparison)而不是==

对于您的示例,这应该有效:

if (string.Equals(txtInput.Text, name, StringComparison.CurrentCultureIgnoreCase))

(而不是if (txtInput.Text == name)

这假设您要使用当前线程的当前文化设置。

或者您可以使用 Daniel White 演示的类似 string.Equals()。

于 2013-05-28T12:20:45.123 回答
0

这应该有效(未经测试!)

string name;
lstResult.Items.Clear();
using (StreamReader sr = File.OpenText("../Name_Check.txt"))
{
    while ((name = sr.ReadLine()) != null)
    {
        if (txtInput.Text.Equals(name, StringComparison.InvariantCultureIgnoreCase))
        {
            lstResult.Items.Add(name);
于 2013-05-28T12:22:54.333 回答