我需要比较两个忽略空格和换行符的字符串,因此以下字符串应该相等:
"Initial directory structure.\r\n \r\n The directory tree has been changed"
"Initial directory structure.\n\nThe directory tree has been changed"
我该如何实施?
怎么样:
string stringOne = "ThE OlYmpics 2012!";
string stringTwo = "THe\r\n OlympiCs 2012!";
string fixedStringOne = Regex.Replace(stringOne, @"\s+", String.Empty);
string fixedStringTwo = Regex.Replace(stringTwo, @"\s+", String.Empty);
bool isEqual = String.Equals(fixedStringOne, fixedStringTwo,
StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isEqual);
Console.Read();
另一种方法是使用 String.Compare 的 CompareOptions。
CompareOptions.IgnoreSymbols
指示字符串比较必须忽略符号,例如空格字符、标点符号、货币符号、百分号、数学符号、和号等。
String.Compare("foo\r\n ", "foo", CompareOptions.IgnoreSymbols);
https://docs.microsoft.com/en-us/dotnet/api/system.globalization.compareoptions
然后复制字符串
xyz.Replace(" ", string.Empty);
xyz.Replace("\n", string.Empty);
怎么样:
string compareA = a.Replace(Environment.NewLine, "").Replace(" ", "");
string compareB = b.Replace(Environment.NewLine, "").Replace(" ", "");
然后你可以比较两者。
也许把它扔到一个辅助函数中:
public bool SpacelessCompare(string a, string b){
string compareA = a.Replace(Environment.NewLine, "").Replace(" ", "");
string compareB = b.Replace(Environment.NewLine, "").Replace(" ", "");
return compareA == compareB;
}
myString = myString.Replace("", "Initial directory structure.\r\n \r\n The directory tree has been changed");
现在只需检查它们是否相等。
String.Compare(myString, "Initial directory structure.The directory tree has been changed")
另一种变体,灵活(添加任何跳过字符),无需修改原始字符串或创建新字符串。
string str = "Hel lo world!";
string rts = "Hello\n world!";
char[] skips = { ' ', '\n' };
if (CompareExcept(str, rts, skips))
Console.WriteLine("The strings are equal.");
else
Console.WriteLine("The strings are not equal.");
static bool CompareExcept(string str, string rts, char[] skips)
{
if (str == null && rts == null) return true;
if (str == null || rts == null) return false;
var strReader = new StringReader(str);
var rtsReader = new StringReader(rts);
char nonchar = char.MaxValue;
Predicate<char> skiper = delegate (char chr)
{
foreach (var skp in skips)
{
if (skp == chr) return true;
}
return false;
};
while (true)
{
char a = strReader.GetCharExcept(skiper);
char b = rtsReader.GetCharExcept(skiper);
if (a == b)
{
if (a == nonchar) return true;
else continue;
}
else return false;
}
}
class StringReader : System.IO.StringReader
{
public StringReader(string str) : base(str) { }
public char GetCharExcept(Predicate<char> compare)
{
char ch;
while (compare(ch = (char)Read())) { }
return ch;
}
}