StreamReader区分大小写
本文关键字:大小写 StreamReader | 更新日期: 2023-09-27 18:04:26
我的程序当前读取一个文本文件,并将其与文本框中的值进行比较,然后告诉我有多少匹配,这目前有效。
我的查询是区分大小写的。有没有办法让它不受大写或小写的影响?
下面是我的代码:if (!String.IsNullOrEmpty(CustodianEAddress.Text))
{
for (AddressLength1 = 0; AddressLength1 < Length; AddressLength1++)
{
List<string> list1 = new List<string>();
using (StreamReader reader = new StreamReader(FileLocation))
{
string line1;
//max 500
string[] LineArray1 = new string[500];
while ((line1 = reader.ReadLine()) != null)
{
list1.Add(line1); // Add to list.
if (line1.IndexOf(cust1[AddressLength1].ToString()) != -1)
{
count1++;
LineArray1[count1] = line1;
}
}
reader.Close();
using (System.IO.StreamWriter filed =
new System.IO.StreamWriter(FileLocation, true))
{
filed.WriteLine("");
filed.WriteLine("The email address " +
cust1[AddressLength1].ToString() + " was found " + count1 +
" times within the recipient's inbox");
}
string count1a;
count1a = count1.ToString();
}
}
}
else
{
MessageBox.Show("Please Enter an Email Address");
}
基本上,我需要将cust1[AddressLength1]
中的值与文本文件中数组中的值进行比较
String.Compare()接受一个可选参数,该参数允许您指定是否应该区分大小写。
对发布的代码进行编辑
的Compare和Index都接受一个可选的枚举StringComparison。如果选择StringComparison。OrdinalIgnoreCase则忽略case
下面是不检查大小写的比较两个字符串的快速方法:
string a;
string b;
string.Compare(a, b, true);
这里的true
是作为ignoreCase
参数的值传递的,这意味着大写字母和小写字母将被比较,就好像它们都是相同的大小写。
我已经清理了一些代码,并且还添加了比较函数。我在修改的地方添加了注释:
// Not needed: see below. List<string> list1 = new List<string>();
using (StreamReader reader = new StreamReader(FileLocation))
{
string line1;
//max 500
List<string> LineArray1 = new List<string>();
while ((line1 = reader.ReadLine()) != null)
{
// list1.Add(line1); // Add to list.
// By adding to the list, then searching it, you are searching the whole list for every single new line - you're searching through the same elements multiple times.
if (string.Compare(line1, cust1[AddressLength1].ToString(), true) == 0)
{
// You can just use LineArray1.Count for this instead. count1++;
LineArray1.Add(line1);
}
}
// Not needed: using() takes care of this. reader.Close();
using (System.IO.StreamWriter filed =
new System.IO.StreamWriter(FileLocation, true))
{
filed.WriteLine(); // You don't need an empty string for a newline.
filed.WriteLine("The email address " +
cust1[AddressLength1].ToString() + " was found " + LineArray1.Count +
" times within the recipient's inbox");
}
string count1a;
count1a = LineArray1.Count.ToString();
}
在比较时,您是否从文件中读取并不重要使用静态字符串比较函数:
public static int Compare(
string strA,
string strB,
bool ignoreCase
)