空白と改行文字を無視して2つの文字列を比較する必要があるため、次の文字列は等しくなります。
"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;
}
}